13

I'm trying to source a file with an environment variable from my bash script, but it doesn't work.

This is the content of my script (test.sh), which is located in ~/scripts/test.sh.

#!/bin/bash
FILE_NAME=/tmp/source_file
touch $FILE_NAME
echo "export TEST=\"test\"" > $FILE_NAME
source $FILE_NAME

Then I use alias in my ~/.bashrc.

alias testScript=~/scripts/test.sh

But when I use my script testScript, it didn't set the environment variable.

3
  • What do you mean by "it didn't set environment variable"? What is your expected result? Commented Oct 27, 2013 at 18:00
  • When I try echo $TEST I don't see any value Commented Oct 27, 2013 at 18:02
  • Does the file /tmp/source_file contain what you expect? Commented Oct 27, 2013 at 18:02

3 Answers 3

11

You need to use:

alias testScript=". ~/scripts/test.sh"

to source the file. Or you can use source in place of ., but I don't much like C shells so I don't use C shell notations such as source.

Sign up to request clarification or add additional context in comments.

Comments

9

Environment variables only flow downstream in the process tree.

When you type testScript to a bash process, it creates a child process and execs /bin/bash or whatever is set by #!

Any environment variables set there remain only with the child process. Export causes the variables to be copied to additional grandchildren (children of that child) that might be spawned from that child.

Nothing can copy back to a parent. You need to use source instead of running the file. See Jonathan's answer.

You could try editing the files ~/.bashrc or ~/.login to set enviornment variables you need frequently.

See also https://superuser.com/q/153371 and https://superuser.com/questions/18988/difference-between-a-b-and-export-a-b-in-bash for more explanation of export in bash.

Comments

4

None of the other methods worked for me [source /path/to/file vs . ./path/to/file, alias, etc...], until, thanks to this tutorial I found that using the:

#!/usr/bin/env bash shebang

instead of the simpler #!/usr/bin/env one lets arguments pass on to the interpreter, which I think is the key here – see this document for more info.

In any event, if source commands in any form aren't working for you, try checking your shebang, that might be the problem :)

1 Comment

This was exactly what I was looking for and should be the accepted answer. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.