How can I make environment variables "exported" in a shell script stick around?

You should source your script, with

. ./script

or

source ./script

When you run a script it gets its own shell and its own environment, which disappear again as soon as the script is finished. To keep the environment variables around, source the script into your current shell:

$ source ./a.sh

or equivalently (but a little more portably) use the POSIX dot command:

$ . ./a.sh

Then the definitions will be put into your current shell's environment and be inherited by any programs you launch from it.

To be closer to running a script, . a.sh will find a.sh by searching the directories in the PATH environment variable.


There are some subtleties in how these behave, and whether . and source are the same (or present at all). . ./a.sh will definitely behave the same in every POSIX-compatible shell, but source and ., and . a.sh and . ./a.sh, can vary. For Bash source and . are the same in all cases; for zsh source always checks the current directory first; ksh is essentially similar.

If the script name is given as a path (containing a /), that path is used directly in all cases. The most portably reliable thing to do is . ./script or . /path/to/script.