Have a Bash script determine it’s own location

1

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" =~ ^/ ]]
then
SCRIPT_LOCATION=$(readlink -f "$0")
else
SCRIPT_LOCATION=$(readlink -f "$(pwd)/""$0")
fi
SCRIPT_DIR=$(dirname $SCRIPT_LOCATION)
echo $SCRIPT_LOCATION
echo $SCRIPT_DIR

Now for a quick test. Lets assume our script is located here:
/home/ryan/scripts/mylocation.sh

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

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

Share.
  • 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.