How can I keep the environment variables, set from a shell script, after the script finishes running?
You can set an environment variable permanently by placing an export command in your Bash shell's startup script " ~/. bashrc " (or "~/. bash_profile ", or " ~/. profile ") of your home directory; or " /etc/profile " for system-wide operations.
To summarize, if you want to set it in current session, then you can do so from the terminal. If you want it to be permanent for a given user, then set it in . bashrc file for that user. If you want to set the variable globally for all users, on a permanent basis, then add it to /etc/environment file.
To store the output of a command in a variable, you can use the shell command substitution feature in the forms below: variable_name=$(command) variable_name=$(command [option ...] arg1 arg2 ...) OR variable_name='command' variable_name='command [option ...]
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
. myScript.sh
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."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With