Last Updated: October 04, 2020
· goldstift

Bash script to switch java version

The following bash script can be used to quickly switch between your installed JDKs on the command line. This can be useful when you need to run a Java application with a specific java version.

$ vi ~/bin/



case "$1" in
                export JAVA_HOME=$JDK6
                export JAVA_HOME=$JDK7
                export JAVA_HOME=$JDK8
                echo "Unknown JDK version! Specify 6, 7 or 8!"

echo "Calling 'java' to output the currently used java version"
java -version

After you made this file executable via chmod u+x ~/bin/ you can run it like . ~/bin/ 7 or source ~/bin/ 7.

NOTE: You'll need the source or . operator to have the variables set in your current shell context!

Happy coding.

Related protips:

How To Check If JDK Is 32-bit or 64-bit?

3 Responses
Add your response

If you need to test your application on different JVMs, you've done something really wrong.

over 1 year ago ·

@zilti Sorry, if I wasn't too precise about this: It's not meant for a single application, but for different applications you start via command line. I have several old applications which don't run with JDK8, yet, which is my command line default at the moment.

Therefore I added the above to each app's "run script" which I found to be redundant and therefore externalized it so I can use it from the scripts as well as from the command line.

over 1 year ago ·

You can also add this to your .bash_profile

alias java6="export JAVA_HOME=`/usr/libexec/java_home -v1.6`"
alias java7="export JAVA_HOME=`/usr/libexec/java_home -v1.7`"

Sometimes you need older JVMs (e.g. you have to build Libs for App Server with only jvm 6 deployed.)

over 1 year ago ·