30

I want to use a shell script that I can call to set some environment variables. However, after the execution of the script, I don't see the environment variable using "printenv" in bash.

Here is my script:

#!/bin/bash

echo "Hello!"
export MYVAR=boubou
echo "After setting MYVAR!"

When I do "./test.sh", I see:

Hello!
After setting MYVAR!

When I do "printenv MYVAR", I see nothing.

Can you tell me what I'm doing wrong?

2 Answers 2

55

This is how environment variables work. Every process has a copy of the environment. Any changes that the process makes to its copy propagate to the process's children. They do not, however, propagate to the process's parent.

One way to get around this is by using the source command:

source ./test.sh

or

. ./test.sh

(the two forms are synonymous).

When you do this, instead of running the script in a sub-shell, bash will execute each command in the script as if it were typed at the prompt.

4
  • It works, but why "bash test.sh" does not set the environment variable? If bash executes each command in the script as if it is typed in the prompt, the environment variable would be set in the current process? Commented Dec 22, 2011 at 13:31
  • 2
    @GDICommander: No. When you run bash test.sh, this creates a new bash process that executes the script and exits.
    – NPE
    Commented Dec 22, 2011 at 13:34
  • 1
    Ok, thanks for the information. Now, I understand environment variables a little bit better. Commented Dec 22, 2011 at 13:51
  • How to run it with sudo ? I get sudo: .: command not found Commented May 8, 2019 at 11:14
4

Another alternative would be to have the script print the variables you want to set, with echo export VAR=value and do eval "$(./test.sh)" in your main shell. This is the approach used by various programs [e.g. resize, dircolors] that provide environment variables to set.

This only works if the script has no other output (or if any other output appears on stderr, with >&2)

1
  • Why the downvote? This is a common pattern and has several advantages.
    – Random832
    Commented Dec 28, 2011 at 16:51

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