2

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.

3
  • What do you mean "when I type"? When you invoke a bash script that does some export, then the "parent" shell that you used to run the script won't see that export? Thus: please see minimal reproducible example and add the relevant part of your code, instead of explaining what your code does. Commented Mar 3, 2022 at 12:44
  • When you type java, the value of JAVA_HOME is irrelevant. As with every command, the shell searches the PATH variable to located the executable. You can do a type -a java to see all the Java versions in your PATH, in search order. Commented Mar 3, 2022 at 13:10
  • Strongly related to this. JAVA_HOME is quite misunderstood and not nearly as important as most people think. Commented Mar 3, 2022 at 13:14

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

0

The commands jdk8, jdk11 or jdk17

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

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.