Home > front end >  How to change java version within a bash script?
How to change java version within a bash script?

Time:03-03

I have one piece of a script that needs a different java version to the rest of the script, up till now I've always manually changed versions with sudo update-alternatives --config java and then just select the one I need.

Is there a way to do that within a bash script?

I've tried export JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64/bin/java which matches the path listed by sudo update-alternatives --config java but if I then type at the command line java -version it still lists the previous java version, and not java-11-openjdk-amd64.

Any help is appreciated.

CodePudding user response:

It depends on the tool used, but for most tools PATH is more important than JAVA_HOME.

Here is a script that changes the path and also restores it

#!/bin/bash
original_path=$PATH

java -version
export PATH=/usr/lib/jvm/java-11-openjdk-amd64/bin/:$PATH
java -version
export PATH=$original_path
java -version

If you directly need to invoke a specific java version a single time in your script then you could also do

PATH=/usr/lib/jvm/java-11-openjdk-amd64/bin/:$PATH java -version
  • Related