'How to change java version within a bash script?

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.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source