Getting the path to a Bash script

If you ever need to perform operations relative to the path of a shell script, the following snippet should be useful:

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

This will give you the absolute path to the script in most cases (see this stack overflow answer for detailed information) - basically in all cases except when the last component (folder) of the path is a symlink.

The code works by getting the path the current script is invoked from - which may be relative in some cases, e.g. if the script is sourced from elsewhere - from an environment variable, and getting its parent directory by feeding it to dirname in a subshell; We then cd into the value returned from this in another subshell and print the working directory.

Newer post
Emperor of Sand
Older post
Deathflix