I have a combination of Java7 and Java8 installed on my 14.04 machine.
When I want to switch between them I do a sudo update-alternatives --config java
. However, changing it this way changes the current Java version on all terminals. I wanted to change it only for the current terminal. For example, I want to test some Java code written in 1.7 against other code, compiled in 1.8.
Another alternative would be doing something like
function java_use() {
export JAVA_HOME=$(/usr/libexec/java_home -v $1)
export PATH=$JAVA_HOME/bin:$PATH
java -version
}
But that works only on my Mac and I wanted something cleaner, without having to modify the PATH
every time. Maybe using chroot
?
How can I "cleanly" change my Java version – preferably only between the installed versions – and only for the current terminal session?
Best Answer
If you look at
/usr/sbin/update-java-alternatives
, you'll see it iterates/usr/lib/jvm/.*.jinfo
to find the installed versions, so you could do the same for detecting the installed versions.As for not modifying
PATH
every time, you can circumventPATH
completely by telling bash which binary it should use for java with the builtinhash
command (runhelp hash
).Here's something you can build on: