How to set a global environment variable in a bash script?
If I do stuff like
#!/bin/bash
FOO=bar
...or
#!/bin/bash
export FOO=bar
...the vars seem to stay in the local context, whereas I'd like to keep using them after the script has finished executing.
Run your script with
.
This will run the script in the current shell environment.
export
governs which variables will be available to new processes, so if you saythen
$BAR
will be available in the environment ofrunScript.sh
, but$FOO
will not.source myscript.sh
is also feasible.Description for linux command
source
:or
man export:
The shell shall give the export attribute to the variables corresponding to the specified names, which shall cause them to be in the environment of subsequently executed commands. If the name of a variable is followed by = word, then the value of that variable shall be set to word.
When you run a shell script, it's done in a sub-shell so it cannot affect the parent shell's environment. You want to source the script by doing:
This executes it in the context of the current shell, not as a sub shell.
From the bash man page: