Make $JAVA_HOME easily changable in Ubuntu

Junho Park picture Junho Park · Apr 16, 2010 · Viewed 286.1k times · Source

In Ubuntu, I'd like to switch my JAVA_HOME environment variable back and forth between Java 5 and 6.

I open a terminal and type in the following to set the JAVA_HOME environment variable:

export JAVA_HOME=/usr/lib/jvm/java-1.5.0-sun

And in that same terminal window, I type the following to check that the environment variable has been updated:

echo $JAVA_HOME

And I see /usr/lib/jvm/java-1.5.0-sun which is what I'm expecting to see. In addition, I modify ~/.profile and set the JAVA_HOME environment variable to /usr/lib/jvm/java-1.5.0-sun.

And now for the problem--when I open a new terminal window and I check my JAVA_HOME environment variable by typing in echo $JAVA_HOME I see that my JAVA_HOME environment variable has been reverted back to Java 6. When I reboot my machine (or log out and back in, I suppose) the JAVA_HOME environment variable is set to Java 5 (presumably because of the modification I made in my ~/.profile).

Is there a way around this so that I can change my JAVA_HOME environment without having to log out and back in (AND make that environment variable change stick in all new terminal windows)?

Answer

Martin Konicek picture Martin Konicek · May 13, 2011

Put the environment variables into the global /etc/environment file:

...
export JAVA_HOME=/usr/lib/jvm/java-1.5.0-sun
...

Execute "source /etc/environment" in every shell where you want the variables to be updated:

$ source /etc/environment

Check that it works:

$ echo $JAVA_HOME
$ /usr/lib/jvm/java-1.5.0-sun

Great, no logout needed.

If you want to set JAVA_HOME environment variable in only the terminal, set it in ~/.bashrc file.