Saturday, October 18, 2014

Setting Global Environment Variables in LINUX

The easiest way to set an environment variable in CentOS is to use export as in :

vanduc@VGN-FZ290E:~/Downloads$export JAVA_HOME=/usr/lib/java/jdk1.7.0_71

vanduc@VGN-FZ290E:~/Downloads$export PATH=$PATH:$JAVA_HOME

However, variables set in such a manner are transient i.e. they will disappear the moment you exit the shell. Obviously this is not helpful when setting environment variables that need to persist even when the system reboots.

In such cases, you need to set the variables within the system wide profile

In CentOS (I’m using v5.2), the folder /etc/profile.d/ is the recommended place to add customizations to the system profile.

For example, when installing the Sun JDK, you might need to set the JAVA_HOME and JRE_HOME environment variables. In this case:
Create a new file called java.sh

vanduc@VGN-FZ290E:~/Downloads$ sudo vi /etc/profile.d/java.sh

Within this file, initialize the necessary environment variables

export JAVA_HOME=/usr/lib/java/jdk1.7.0_71

export JRE_HOME=$JAVA_HOME/jre

export PATH=$PATH:$JRE_HOME/bin

export PATH=$PATH:$JAVA_HOME/bin


Now when you restart your machine, the environment variables within java.sh will be automatically initialized (checkout /etc/profile if you are curious how the files in /etc/profile.d/ are loaded) .

If you want to load the environment variables within java.sh without having to restart the machine, you can use the source command as in:

vanduc@VGN-FZ290E:~/Downloads$ source /etc/profile.d/java.sh


Test command:

vanduc@VGN-FZ290E:~/Downloads$ java -version

java version "1.7.0_71"

Java(TM) SE Runtime Environment (build 1.7.0_71-b14)

Java HotSpot(TM) Server VM (build 24.71-b01, mixed mode)

vanduc@VGN-FZ290E:~/Downloads$

P/S : some common commands use to setup java environment

vanduc@VGN-FZ290E:~/Downloads$ cd Downloads/
vanduc@VGN-FZ290E:~/Downloads$ ls
google-chrome-stable_current_i386.deb jdk-7u71-linux-i586.tar.gz sublime-text_build-3065_i386.deb
vanduc@VGN-FZ290E:~/Downloads$ tar -zxvf jdk-7u71-linux-i586.tar.gz
vanduc@VGN-FZ290E:~/Downloads$ sudo mkdir /usr/lib/java
vanduc@VGN-FZ290E:~/Downloads$ mv jdk1.7.0_71/ /usr/lib/java/


No comments:

Post a Comment