How can I keep the environment variables, set from a shell script, after the script finishes running?
-
Use the export command: http://stackoverflow.com/questions/7328223/unix-export-command – congusbongus Feb 07 '13 at 02:09
-
Add them to the file `~/.bash_profile`. – Feb 07 '13 at 02:09
-
3@CongXu `export` passes variables down to the child, not up to the parent. – Beta Feb 07 '13 at 02:11
-
Why are you asking? Why do you want to keep those environment variables? Do you really care about keeping all of them? Why does keeping e.g. `WINDOWID` or `SSH_AGENT_PID` is important to you? – Basile Starynkevitch Feb 07 '13 at 06:36
-
You could also make your script a bash `function` defined in your `$HOME/.bashrc` – Basile Starynkevitch Feb 07 '13 at 06:37
3 Answers
This is not possible by running the script. The script spawns it's own sub-shell which is lost when the script completes.
In order to preserve export
s that you may have in your script, call it
- either as
. myScript.sh
- or
source myScript.sh
Notice the space between the .
and myScript.sh
; also note that "source
is a synonym for .
in Bash, but not in POSIX sh
, so for maximum compatibility use the period."

- 6,300
- 3
- 46
- 67

- 4,245
- 1
- 22
- 47
run the script as follows:
source <script>
-OR-
. <script>
This will run the script in the current shell, and define variables in the current shell. The variables will then be retained in the current shell after the script is done.

- 8,779
- 4
- 29
- 57
Environment variables exist the the environment that is private to each process. The shell passes a COPY of exported variables to it's children as their environment, but there is no way for them to pass their environment back to the parent or any process other than their children.
You can print those variables and load them into the parent.
Or as has been already mentioned, you can run your script in the current shell with either "source script" or ". script" (and you might need ./script if . isn't in your PATH).
Some tools print their vars and the shell can load them using backticks like ssh-agent
. That way whatever ssh-agent prints will be run as a command. If it prints something like "VAR1=VAL;VAR2=VAL2" that may do what you want.

- 571
- 3
- 10