Last Updated: February 25, 2016
·
326
· quekshuy

[Shell] Getting the directory of the running script

This was troublesome.

Needed to get the directory of the running script that I run using source

Normally in a shell script you can use the variable $0 but this changes when using source.

Bo bian.

I copied the below line from ansible, which uses a similar setup in its env-setup script:

# When run using source as directed, $0 gets set to bash, so we must use $BASH_SOURCE
if [ -n "$BASH_SOURCE" ] ; then
    SETUP_DIR=`dirname $BASH_SOURCE`
else
    SETUP_DIR="$PWD"

This works.