How do I get the path of the directory in which a Bash script is located, inside that script?
For instance, let's say 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
None of these worked for a bash script launched by Finder in OS X - I ended up using:
Not pretty, but it gets the job done.
So... I believe I've got this one. Late to the party, but I think some will appreciate it being here is them come across this thread. The comments should explain.
The best compact solution in my view would be:
There is no reliance on anything other than Bash. The use of
dirname
,readlink
andbasename
will eventually lead to compatibility issues, so they are best avoided if at all possible.I am tired of coming to this page over and over to copy paste the one-liner in the accepted answer. The problem with that is it is not easy to understand and remember.
Here is an easy-to-remember script: