Always run a shell script from the directory it lives in
01 November 2017
Always run a shell script in the directory in which it appears, and change back to the directory you were in when you ran it even if it fails.
trap popd EXIT pushd $PWD cd $(dirname "$0")
Works for me in bash. The
pushd command does a
but saves the directory where you were on a stack, and
popd pops the saved directory from the stack. The
trap ... EXIT is a bash way to run something when
the script exits, no matter how, and
is the directory name of the script.
(Taken from the
deploy.sh script that rebuilds and
deploys this blog, so if you can read this, it works.)