645

I'm running Ubuntu 11.04. I use the terminal to start a bash session, and I want to add an environment variable:

$r@hajt:~$ env THEVAR=/example

But it's not working. It shows all the variables with THEVAR being the last one, but another call to env does not show THEVAR anymore- env | grep THEVAR returns nothing.

Similarly, scripts with export (export THEVAR=/example) or other variable assignments (THEVAR=/example) don't add the environment variable.

I know I'm doing something wrong, I know it should be something simple, but I just can't find what.

UPDATE: The real meaning of my question was this one:

(Anyway I'll choose the most voted answer and leave the edited title -that wasn't what I was asking)

env runs a program in a modified environment, then dismisses all the changes.

Paul
  • 4,511
huff
  • 6,550

8 Answers8

985

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.

Use source ~/.bashrc in your terminal for the changes to take place immediately.

cocomac
  • 3,394
  • 60
    Shell config files such as ~/.bashrc, ~/.bash_profile, and ~/.bash_login are often suggested for setting environment variables. While this may work on Bash shells for programs started from the shell, variables set in those files are not available by default to programs started from the graphical environment in a desktop session. https://help.ubuntu.com/community/EnvironmentVariables – SudoSURoot Aug 22 '15 at 08:38
  • Where should I add my specific line?! bottom of .bashrc page?! – Dr.jacky Dec 06 '15 at 05:41
  • 1
    @Mr.Hyde yes, that's probably a reasonable place – Michał Šrajer Dec 07 '15 at 16:55
  • Why is the second one less portable? –  Mar 17 '16 at 01:22
  • 1
    @BharadwajRaju because on some old UNIX systems one can export only variable that is set already. Old Solaris and HP-UX for example. – Michał Šrajer Mar 18 '16 at 17:19
  • 1
    Once you set environment variable, how can I quickly view it to make sure it is set? – Rod Sep 27 '18 at 13:54
  • 6
    @Rod echo $myvar – Qwerty Oct 16 '18 at 12:35
  • 1
    I like the full verbosity of this reply. It fully explains the situation. – Robert Wm Ruedisueli Nov 27 '19 at 16:52
  • This did not work for me. I want to add /opt/microchip/xc8/v2.10/bin/xc8 and use only xc8, instead of /opt/microchip/xc8/v2.10/bin/xc8 every time. – CFCBazar Jun 22 '20 at 16:15
  • 1
    You can use source ~/.bashrc to reload variables in bashrc without logout. – Emoji May 24 '21 at 05:02
49

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:

Manuel Jordan
  • 1,768
  • 7
  • 30
  • 50
Lesmana
  • 18,386
  • 7
    How can I make it work only by executing the script ? Without sourcing. – Mithril Nov 09 '17 at 01:53
  • @Lesmana You can't. See the link at the end at for the explanation why: "When you execute the script you are opening a new shell, type the commands in the new shell, copy the output back to your current shell, then close the new shell. Any changes to environment will take effect only in the new shell and will be lost once the new shell is closed." – Thorbjørn Lindeijer Jan 14 '24 at 11:24
28

To permanently add a new environment variable in Ubuntu (tested only in 14.04), use the following steps:

  1. Open a terminal (by pressing CtrlAltT)
  2. sudo -H gedit /etc/environment
  3. Type your password
  4. Edit the text file just opened:
    e.g. if you want to add FOO=bar, then just write FOO=bar in a new line
  5. Save it
  6. Once saved, logout and login again.
  7. Your required changes are made.
muru
  • 197,895
  • 55
  • 485
  • 740
  • 7
    I have cleaned up your answer removing the more dangerous bits about sudo gedit (See http://askubuntu.com/questions/270006/why-user-should-never-use-normal-sudo-to-start-graphical-application) and chmod 777. The latter should never be done on a system configuration file. – muru Dec 08 '14 at 13:45
  • This is a correct answer for certain cases. All sessions, whether user shell sessions or not will get the value of variables set here. It is important to note that while this may look like a shell script, it is not -- it allows you only to set environment variables (vs. using shell functions like if or test) – Tom Harrison Jr Nov 09 '16 at 18:44
  • If bar is a string, should I put it between quotation marks? Like Foo="bar"? – blue_chip Nov 10 '16 at 17:33
  • @blue_chip No, works without quotes. – Click Upvote Jan 10 '17 at 03:20
  • 5
    @blue_chip for environment variables, everything is a string. You only need quotes when it contains spaces. – Ruslan Feb 03 '17 at 14:40
20

To get the environment/var changes to persist after the script has completed, you have to usesource ./script.sh or the shorthand notation for source, ".", like . ./script.sh

Source will execute the commands in the script as if you have typed them in... so it does change some aspects of the script, such as exiting... so if your script checks something and decides to exit if false, for instance, via calling exit 0, it will terminate your current terminal / shell session.

m0bl
  • 301
  • 2
  • 2
  • This is a very old question that already has an accepted answer and a few others... Consider, answering more recent questions please... – NerdOfCode Mar 16 '18 at 18:13
  • 8
    @NerdOfCode this answer addresses a problem that is still relevant and none of the other answers, including the accepted one, mention it, as far as I can see... There are in fact two badges available for providing good answers to old questions, so this is encouraged – Zanna Mar 27 '18 at 20:08
  • 2
    This exactecly what was I looking for. I needed to see out of the script, the exported variables from the script. – albanx Mar 11 '19 at 13:01
  • 5
    @NerdOfCode how on the Earth can you discourage someone from providing additional information? This answer solved all my problems! – Luca Fagioli Apr 02 '20 at 07:59
12

I know it's pretty late, but if you want to add an environment variable for all users (e.g. JAVA usage) - you can do the following:

1) Open /etc/bash.bashrc using nano (you can use whatever editor, I do not prefer VIM as it's the worst when it comes to user friendliness - nothing personal).

2) Append to the file:

export VAR=path export PATH=$PATH:/bin 3) (Better if you can bounce the box) - or simply open a new SSH session and confirm using `env' command.

BUT IF you want each user to have a separate setting for this, you have to make a change (scripted) to .bashrc file under ~/.bashrc (or /home/$USER/ if you are new to Linux systems)

ha9u63a7
  • 261
  • 2
  • 6
  • This helped me fix my ~/.bashrc. As you say, it looks like it must be PATH=$PATH:/bin, I had $PATH:/bin=PATH which seemed to work but came up with errors. – sdexp Dec 30 '19 at 11:01
9

If you are doing things via script, one easy way to set environment variable permanently is put below statement in your script,

if [[ ! -d "$MyVar" ]]; then 
    export MyVar="abc"
    echo 'export MyVar="abc"' >> ~/.bashrc
fi

If you need to evaluage expressions like pwd, you can use this, for example,

echo "export EIGEN_ROOT=\"$(pwd)/eigen\"" >> ~/.bashrc
3

If you are using Ubuntu or any Unix-based system then export the variables in the ~/.bashrc file. It's a hidden file and you can get there through the terminal or by unhiding hidden files in the file system.

Then edit the file and set export THEVAR=/example there, save and it's done.

2

If you are deploying JAVA aplication using TOMCAT you can set environment variables the following way:

1.sudo su and cd to /var/lib/tomcat8/bin/ (or whichever is your tomcat bin path)

  1. touch setenv.sh(if it doesn't exist), if file present already do 'vi setenv.sh'

  2. chmod 777 setenv.sh (make file executable)

  3. vi setenv.sh and set following line in setenv.sh export key=value

  4. sudo systemctl restart tomcat.service

In your java file you can use the following code to check if the variable is set

private static void printEnv() {
    System.out.println("******************************Environment Vars*****************************");
    Map<String, String> enviorntmentVars = System.getenv();
    enviorntmentVars.entrySet().forEach(System.out::println);
System.out.println(&quot;******************************system Vars*****************************&quot;);
Properties enviorntmentProperties = System.getProperties();
enviorntmentVars.entrySet().forEach(System.out::println);

}