How to get a script’s directory reliably in Bash on Linux?

How to get a script’s directory reliably in Bash on Linux?

For example, to get the directory of the executing script $0.

dirname can give you the directory name from the absolute path.

You can get the absolute path of the script by readlink -f to handle symbolic links (consider a symbolic link ./run.sh linked to ../../run.sh, dirname ./run.sh will give you .), and then pass the absolute path to dirname.

In summary, the script the get the directory of current script is:

directory=$(dirname $(readlink -f $0))

or

directory=$(dirname $(readlink -f ${BASH_SOURCE[0]}))

to also handle sourced bash script. Check http://ask.systutorials.com/2077/how-to-get-the-scripts-own-path-in-sourced-bash-script for details of the ${BASH_SOURCE[0]} meaning.

Answered by Eric Z Ma.

Eric Z Ma

Eric is a father and systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

Leave a Reply

Your email address will not be published. Required fields are marked *