Get Path to Currently Executing Bash Script

Last modified: 
Friday, March 4th, 2016

This Bash one-liner should return the full path to the script from which it is being executed.

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

The above may not work as expected with symlinks. A more robust (and verbose) solution is as follows:

# 
# Returns the full path to the script it is called in.
#
function SCRIPT_DIR() {
    SCRIPT_DIR=''
    SOURCE="${BASH_SOURCE[0]}"
    while [ -h "$SOURCE" ]; do
        SCRIPT_DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
        SOURCE="$(readlink "$SOURCE")"
        [[ $SOURCE != /* ]] && SOURCE="$SCRIPT_DIR/$SOURCE" 
    done
    SCRIPT_DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
}

References

Can a Bash script tell what directory it's stored in?


The operator of this site makes no claims, promises, or guarantees of the accuracy, completeness, originality, uniqueness, or even general adequacy of the contents herein and expressly disclaims liability for errors and omissions in the contents of this website.