Switch between JDKs at the command-line

Here’s the script that I use on macosx to switch JDKs in consoles. It can easily be adapted for any unixish system.

export JDK=/System/Library/Frameworks/JavaVM.framework/Versions/$1/Home/

if [[ -d $JDK ]]
then
echo "using $JDK as the current jdk..."
export JAVA_HOME=$JDK
export PATH=$JAVA_HOME/bin:$PATH
else
echo "setjdk error: $JDK directory does not exist"
fi

Use it like . setjdk 1.4.2, don’t forget the initial dot and space which mean “execute this script without starting a new process”, so that the JAVA_HOME and PATH defined in the script are valid for your current shell.

Thanks Helma for asking about this, it’s good to know that this entry can actually be useful to some people, as opposed to just noise ;-)

2 Responses to Switch between JDKs at the command-line

  1. cheers says:

    This is a pedantic bug report:

    If you do:

    . setjdk 1.4.2
    . setjdk 1.4.2
    . setjdk 1.4.2
    . setjdk 1.5.0
    . setjdk 1.4.2
    . setjdk 1.4.2
    . setjdk 1.4.2

    say 1000 times you end up with a huge PATH full of jdk stuff.

    Suggestion:

    1. Either constrain to few switches (with a count variable)

    2. Or save the PATH under ORIG_PATH on first switch and then use ORIG_PATH to set the new PATH with the new JDK.

    -c from cheers

  2. You’re right (in a pedantic way ;-) but IRL this is not really a problem, the way I use my consoles at least – they don’t live that long.

    The “right” way might be to remove other jvms from the PATH using regexps.

%d bloggers like this: