Setting environment variable in shell script does not make it visible to the shell Setting environment variable in shell script does not make it visible to the shell unix unix

Setting environment variable in shell script does not make it visible to the shell


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.


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)