How do I get the path of the directory in which a Bash script is located, inside that script?
I want to use a Bash script as a launcher for another application. I want to change the working directory to the one where the Bash script is located, so I can operate on the files in that directory, like so:
$ ./application
is a useful one-liner which will give you the full directory name of the script no matter where it is being called from.
It will work as long as the last component of the path used to find the script is not a symlink (directory links are OK). If you also want to resolve any links to the script itself, you need a multi-line solution:
This last one will work with any combination of aliases,
source,bash -c, symlinks, etc.Beware: if you
cdto a different directory before running this snippet, the result may be incorrect!Also, watch out for
$CDPATHgotchas, and stderr output side effects if the user has smartly overridden cd to redirect output to stderr instead (including escape sequences, such as when callingupdate_terminal_cwd >&2on Mac). Adding>/dev/null 2>&1at the end of yourcdcommand will take care of both possibilities.To understand how it works, try running this more verbose form:
And it will print something like: