Have a Bash script determine it’s own location


At some point it may be helpful to have a BASH script dynamically determine the location of itself when executed from anywhere on the system. The following code will produce the canonicalized absolute pathname of the script, as well as the directory that it resides in.

The script first determines if the the first argument which is a path to the script is a relative or absolute path. If it is a relative path it will prepend the current working directory. Finally the entire path is canonicalized which resolves all symlinks and removes the extra “./”, “../” and ‘/’ characters.

Here is the script:

if [[ "$0" =~ ^/ ]]
SCRIPT_LOCATION=$(readlink -f "$0")
SCRIPT_LOCATION=$(readlink -f "$(pwd)/""$0")

Now for a quick test. Lets assume our script is located here:

Executing the script in the same directory:
$ ./mylocation/home/ryan/scripts/mylocation.sh

Executing in another directory with the absolute path produces the same results:
$ /home/ryan//////scripts/../scripts/mylocation.sh/home/ryan/scripts/mylocation.sh

  • Visitor

    Actually, readlink deals with relative paths and there is no need to prepend current directory. Prepending current directory can also be harmful if the script is invoked through the path.