kellogg76
kellogg76

Reputation: 31

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.

Upvotes: 1

Views: 9784

Answers (2)

Najm
Najm

Reputation: 1

The commands jdk8, jdk11 or jdk17

will change the version of java in git bash depending on what version you have installed.

Upvotes: 0

ckoidl
ckoidl

Reputation: 362

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

Upvotes: 3

Related Questions