Shell – Updating environment variable in a shell script

environment-variablesshell-script

I am trying to update the value of an environment variable in a third party shell script. My OS is Oracle Linux Server release 6.4 (Red Hat Enterprise Linux Server release 6.4 (Santiago).

I already have the below environment variables defined in /etc/bashrc (for all users)

JAVA_HOME=/opt/java/jdk1.8.0_45
PATH=$PATH:$HOME/bin:$JAVA_HOME/bin

export JAVA_HOME
export PATH

I would like to use a different jdk installation for one of the shell script. Hence I add the below lines to customscript.sh

JAVA_HOME=/opt/java/jdk1.7.0_79
export JAVA_HOME
echo "PATH variable is $PATH"
...                      #other script code

The customscript.sh still defaults to the old environment variable value for the PATH variable. The output of the above echo command shows that it is still referring to the old JAVA_HOME variable value.

What could I be missing?

Best Answer

Your /etc/bashrc sets PATH by interpreting $JAVA_HOME's value at that moment. It does not get re-interpreted if JAVA_HOME changes later. You'll want to add a line to the 3rd-party shell script that says: PATH=$JAVA_HOME:$PATH so that the 1.7 JAVA_HOME is put into the path before the /etc/bashrc's 1.8 JAVA_HOME.

Related Question