Script to hot switch JDK versions in Mac OS X terminals
Personal note.
Here is a script that lets you switch your JDK version in a terminal window. It also has auto completion.
Put the script in a file and add
source filename
in ~/.profile or ~/.bash_profile and you will be able to call setjdk and use autocompletion (with <tab>) from the command line.
emmanuel@computer $ setjdk 1.<tab>emmanuel@computer $ setjdk 1.5
Original version at codehaus.
#!/bin/bashfunction defaultjdk {
local vmdir=/System/Library/Frameworks/JavaVM.framework/Versions
local ver=${1?Usage: defaultjdk }
[ -z "$2" ] || error="Too many arguments"
[ -d $vmdir/$ver ] || error="Unknown JDK version: $ver"
[ "$(readlink $vmdir/CurrentJDK)" != "$ver" ] || error="JDK already set to $ver"
if [ -n "$error" ]; then
echo $error
return 1
fi
echo -n "Setting default JDK & HotSpot to $ver ... "
if [ "$(/usr/bin/id -u)" != "0" ]; then
SUDO=sudo
fi
$SUDO /bin/rm /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK
$SUDO /bin/ln -s $ver /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK
echo Done.
}
function setjdk {
local vmdir=/System/Library/Frameworks/JavaVM.framework/Versions
local ver=${1?Usage: setjdk }
[ -d $vmdir/$ver ] || {
echo Unknown JDK version: $ver
return 1
}
echo -n "Setting this terminal's JDK to $ver ... "
export JAVA_HOME=$vmdir/$ver/Home
PATH=$(echo $PATH | tr ':' '\n' | grep -v $vmdir | tr '\n' ':')
export PATH=$JAVA_HOME/bin:$PATH
java -version
}
function _setjdk_completion (){
COMPREPLY=()
local vmdir=/System/Library/Frameworks/JavaVM.framework/Versions
local cur=${COMP_WORDS[COMP_CWORD]//\\\\/}
local options=$(cd $vmdir; ls | grep 1. | tr '\n' ' ')
COMPREPLY=($(compgen -W "${options}" ${cur}))
}
complete -F _setjdk_completion -o filenames setjdk
complete -F _setjdk_completion -o filenames defaultjdk
Comments