Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preserve environments vars after shell script finishes

How can I keep the environment variables, set from a shell script, after the script finishes running?

like image 948
yukon Avatar asked Feb 07 '13 02:02

yukon


People also ask

How do I set environment variables permanently in Linux?

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.

How do I permanently set environment variables in Ubuntu?

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.

How do you store shell variables?

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 ...]


1 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 exports 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."

like image 162
Tyler Jandreau Avatar answered Sep 21 '22 17:09

Tyler Jandreau