Shell script that determines its own location

Posted 12 June 2008

Based on some notes from this page , I wrote the following in a shell script to determine the absolute path to the script if the script is called from the command line using a relative path:

#! /bin/bash ScriptLocation="`pwd`"/"`dirname $0`"

`dirname $0` is the relative path to the script from the current working directory. I add `pwd`, the absolute path to the current working directory, to obtain the absolute path to the script.

If the script is called from an absolute path, such as /Users/josh/location_aware.sh, this outputs a nonsense path: /Users/josh//Users/josh. This is because $0 is the name of the file that Bash is invoked with. If Bash is invoked with an absolute path, then `dirname $0` will be an absolute path. I added a few more lines of code to check whether $0 was a relative path and wound up with the following:

#! /bin/bash if [[ $0 == '/'* ]]; then ScriptLocation="`dirname $0`" else ScriptLocation="`pwd`"/"`dirname $0`" fi

These snippets output the directory in which the script resides; replace `dirname $0` with $0 to obtain the path to the script file itself.

Comment