How To Find Bash Script Directory Within Script
By Angsuman Chakraborty, Gaea News NetworkSunday, September 14, 2008
One of the common challenges bash script writers face when writing a script which references files in the same directory (or its sub-directories) as the script file. As the script can be called from anywhere, you cannot use the current directory to refer to the files. You really need to refer to the directory the script is located. One way is to hardcode the script directory and set it in the installation script. But that fails when you don’t have an installation script or when user moves the script directory to a different location. I am sure you will agree that it is a clumsy solution. Is there a better way?
The bash script
The idea is to cd to the script directory and execute your commands from there. But how can you cd to the script directory?
cd “`dirname $0`”
What this command does is extract the directory from the path which was used to invoke the script. This path can be a relative path. However since cd is done from the current directory, it will be fine. In short this trick can be used in any situation and saves you from hardcoing the script directory within the script.
You can use the concept with other shells too like ksh or csh or sh. Give it a try.
Epilogue
I didn’t arrive at the above script in the first try. First I wrote:
cd “$PWD/`dirname $0`”
This works too but is slightly uglier that above. Then I realized that I could write something much simpler:
cd `dirname $0`
This will work in all situations except when the path contains spaces.
March 19, 2010: 1:32 pm
This method unfortunately doesn’t work if no path was specified when the script was called (such as when the script is in the PATH). |
Micha |
Thanos |
Jason R. Coombs