How do I add environment variables?
To set variable only for current shell:
VARNAME="my value"
To set it for current shell and all processes started from current shell:
export VARNAME="my value" # shorter, less portable version
To set it permanently for all future bash sessions add such line to your .bashrc
file in your $HOME
directory.
To set it permanently, and system wide (all users, all processes) add set variable in /etc/environment:
sudo -H gedit /etc/environment
This file only accepts variable assignments like:
VARNAME="my value"
Do not use the export
keyword here.
You need to logout from current user and login again so environment variables changes take place.
To set an environment variable once, use the export
command in the prompt, not in a shell script:
$ export THEVAR=/example
The variable will be set for the rest of the shell session or until unset.
To set an environment variable everytime, use the export
command in the .bashrc
file (or the appropriate initialization file for your shell).
To set an environment variable from a script, use the export
command in the script, and then source
the script. If you execute the script it will not work.
For an explanation of the difference between sourcing and executing see this answer: https://superuser.com/questions/176783/what-is-the-difference-between-executing-a-bash-script-and-sourcing-a-bash-script/176788#176788
To permanently add a new environment variable in Ubuntu (tested only in 14.04), use the following steps:
- Open a terminal (by pressing CtrlAltT)
sudo -H gedit /etc/environment
- Type your password
- Edit the text file just opened:
e.g. if you want to addFOO=bar
, then just writeFOO=bar
in a new line - Save it
- Once saved, logout and login again.
- Your required changes are made.