Way to get the path of a bash script when used in the source command

bashcommand line

I want to set an environment variable relative to the location of a script. I can easily find and set it for the duration of the script (test.sh):

#!/bin/bash
export MY_VARIABLE=$(dirname $0)
echo MY_VARIABLE is : $MY_VARIABLE

Call:

./test.sh

Output:

MY_VARIABLE is : .

If I want to use the variable in other scripts, I need to set it with the source command. This is of course not working because I'm now not calling the test.sh script, but the source command.

source test.sh

Output:

dirname: illegal option -- b
usage: dirname path
MY_VARIABLE is :

Is there a way to define an environment variable in a script that can then be used with the source command?

Best Answer

test2.sh:

#!/bin/bash
MY_VARIABLE=$(PWD)/$(dirname $BASH_SOURCE)
echo MY_VARIABLE is : $MY_VARIABLE

Call:

./test2.sh

Output:

MY_VARIABLE is : /some/path/.

Call:

source ./test2.sh

Output:

MY_VARIABLE is : /some/path/.

Thanks @webmark and @GordonDavisson.

Related Question