Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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?

share|improve this question
    
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

1 Answer 1

up vote 1 down vote accepted

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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