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.

asked Dec 16, 2015 by anonymous

1 Answer

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 Dec 16, 2015 by Eric Z Ma (44,280 points)
edited Feb 13, 2016 by Eric Z Ma

Please log in or register to answer this question.

Copyright © SysTutorials. User contributions licensed under cc-wiki with attribution required.
Hosted on Dreamhost

...