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:
Executing in another directory with the absolute path produces the same results: