Skip to content

Instantly share code, notes, and snippets.

@alanmur
Last active December 9, 2021 13:38
Show Gist options
  • Save alanmur/387e81c6fd79a44656c1bc43a216396d to your computer and use it in GitHub Desktop.
Save alanmur/387e81c6fd79a44656c1bc43a216396d to your computer and use it in GitHub Desktop.
Getting the absolute script path of a shell script

Getting the absolute script path of a shell script

# Directory script was called from
PWD="$(pwd)"
# Path part of the command line (caveats http://mywiki.wooledge.org/BashFAQ/028)
DIRNAME=$(dirname -- "$0")
# Calculate absolute directory name
if [[ $DIRNAME =~ ^/ ]] ; then
    ABSDIRNAME="$(cd "${DIRNAME}"; pwd)"
else
    ABSDIRNAME="$(cd "${PWD%/}"/"${DIRNAME}"; pwd)"
fi
# Base filename
BASENAME=$(basename -- "$0")
# Absolute script filename
ABSNAME="$ABSDIRNAME/$BASENAME"

echo Called from
echo PWD: $PWD
echo Path of script on command line
echo DIRNAME: $DIRNAME
echo Absolute path of script
echo ABSDIRNAME: $ABSDIRNAME
echo base name of file
echo BASENAME: $BASENAME
echo absolute name of script
echo ABSNAME: $ABSNAME
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment