Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set bash environment variables from a script?

Tags:

I have some proxy settings that I only occasionally want to turn on, so I don't want to put them in my ~/.bash_profile. I tried putting them directly in ~/bin/set_proxy_env.sh, adding ~/bin to my PATH, and chmod +xing the script but though the script runs, the variables don't stick in my shell. Does anyone know how to get them to stick around for the rest of the shell session?

like image 901
James A. Rosen Avatar asked Jun 17 '10 19:06

James A. Rosen


People also ask

How do I set an environment variable in shell?

You can set your own variables at the command line per session, or make them permanent by placing them into the ~/. bashrc file, ~/. profile , or whichever startup file you use for your default shell. On the command line, enter your environment variable and its value as you did earlier when changing the PATH variable.

How do you set a variable value in bash?

To create a variable, you just provide a name and value for it. Your variable names should be descriptive and remind you of the value they hold. A variable name cannot start with a number, nor can it contain spaces. It can, however, start with an underscore.

Where does bash Get environment variables?

You can set your own persistent environment variables in your shell configuration file, the most common of which is ~/. bashrc. If you're a system administrator managing several users, you can also set environment variables in a script placed in the /etc/profile.


2 Answers

Use one of:

source <file>  . <file> 
like image 166
mob Avatar answered Oct 30 '22 00:10

mob


In the script use

export varname=value

and also execute the script with:

source set_proxy_env.sh.

The export keyword ensures the variable is marked for automatic inclusion in the environment of subsequently executed commands. Using source to execute a script starts it with the present shell instead of launching a temporary one for the script.

like image 42
Amardeep AC9MF Avatar answered Oct 30 '22 00:10

Amardeep AC9MF