How to get a script’s directory reliably in Bash on Linux?
Posted on In QAHow 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 https://www.systutorials.com/241594/how-to-get-the-scripts-own-path-in-sourced-bash-script/ for details of the ${BASH_SOURCE[0]}
meaning.