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/switch_java_to.sh
#!/bin/bash
JDK6=/System//Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/
JDK7=/Library//Java/JavaVirtualMachines/jdk1.7.0_25.jdk/Contents/Home/
JDK8=/Library//Java/JavaVirtualMachines/jdk1.8.0.jdk/Contents/Home/
case "$1" in
"6")
export JAVA_HOME=$JDK6
;;
"7")
export JAVA_HOME=$JDK7
;;
"8")
export JAVA_HOME=$JDK8
;;
*)
echo "Unknown JDK version! Specify 6, 7 or 8!"
;;
esac
export JDK_HOME=$JAVA_HOME
echo "Calling 'java' to output the currently used java version"
java -version
After you made this file executable via chmod u+x ~/bin/switch_java_to.sh
you can run it like . ~/bin/switch_java_to.sh 7
or source ~/bin/switch_java_to.sh 7
.
NOTE: You'll need the source
or .
operator to have the variables set in your current shell context!
Happy coding.
Related protips:
Written by Alex Heusingfeld
Related protips
3 Responses
If you need to test your application on different JVMs, you've done something really wrong.
@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.
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.)