5

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?

3
  • See this SO question, and BashFAQ #28. – Gordon Davisson Apr 7 '14 at 15:22
  • 1
    @GordonDavisson Thank you for the hint. Using $BASH_SOURCE instead of $0 works fine and I can solve my problem. I only lack 4 reputation to answer the question and accept the answer, so here is the answer in the comment. This solution works fine for relative paths, which is ok in my case: test.sh #!/bin/bash echo pwd/dir : $(PWD)/$(dirname $BASH_SOURCE) – Sacha Guyer Apr 9 '14 at 9:55
  • @SachaGuyer, just gave you some up votes, you should have the rep to do this now. – webmarc Sep 15 '14 at 17:37
2

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.