I have written a script to change the java environment variables of the shell:
#!/bin/bash
#env variables can be changed only if we call the script with source setJavaVersion.sh
case $1 in
6)
export JAVA_HOME=/atgl/product/java/jdk-1.6.0_43/linux-redhat_x86_64/jdk1.6.0_43/
export PATH=$JAVA_HOME:$PATH ;
;;
7)
export JAVA_HOME=/atgl/product/java/jdk-1.7.0_51/linux-redhat_x86_64/jdk1.7.0_51
export PATH=$JAVA_HOME:$PATH ;
;;
8)
export JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.91-0.b14.el7_2.x86_64/jre/
export PATH=$JAVA_HOME:$PATH ;
;;
*)
error java version can only be 1.6, 1.7 or 1.8
;;
esac
To execute it, I enter:
source setJavaVersion.sh 6
to set the environment with jdk6, source setJavaVersion.sh 7 for jdk7 and so.
when I look at the environment variables with:
$ echo $JAVA_HOME
and
$ echo $PATH
I see that the variables are well updated.
However, when I execute the command
java -version
it is not updated.
If I enter the same export commands directly in the shell, java -version returns the updated result.
Why ?
Edit: I have updated my script with the deathangel908 answer. Here is the output of which java and PATH before and after the script execution:
$ which java
/atgl/product/java/jdk-1.7.0_51/linux-redhat_x86_64/jdk1.7.0_51/bin/java
$ echo $PATH
/CPD/SDNT/tools/bin:/CPD/SDNT/tools/x86_64-pc-unix11.0/bin:/atgl/product/java/jdk-1.7.0_51/linux-redhat_x86_64/jdk1.7.0_51/bin:/CPD/SDNT/tools/bin:/CPD/SDNT/tools/x86_64-pc-unix11.0/bin:/atgl/product/java/jdk-1.7.0_51/linux-redhat_x86_64/jdk1.7.0_51/bin:/usr/lib64/qt-3.3/bin:/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin:/users/t0059888/bin:/users/t0059888/bin
$ source setJavaVersion 6
$ which java
/atgl/product/java/jdk-1.7.0_51/linux-redhat_x86_64/jdk1.7.0_51/bin/java
$ echo $PATH
/CPD/SDNT/tools/bin:/CPD/SDNT/tools/x86_64-pc-unix11.0/bin:/atgl/product/java/jdk-1.7.0_51/linux-redhat_x86_64/jdk1.7.0_51/bin:/CPD/SDNT/tools/bin:/CPD/SDNT/tools/x86_64-pc-unix11.0/bin:/atgl/product/java/jdk-1.7.0_51/linux-redhat_x86_64/jdk1.7.0_51/bin:/usr/lib64/qt-3.3/bin:/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin:/users/t0059888/bin:/users/t0059888/bin:/atgl/product/java/jdk-1.6.0_43/linux-redhat_x86_64/jdk1.6.0_43/
update-java-alternatives.