Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 5.3

Nice little script for OSX

Simply source this file while initializing your environment. This will give you two commands:

setjdk - set the jdk for just a terminal
defaultjdk - set the jdk for the system (all future terminals and java applications). Will prompt you for a password.

Each has tab completion, such as:

No Format
$ setjdk 1.<hit tab>
1.3    1.3.1  1.4    1.4.2  1.5    1.5.0

Usage

Run as follows:

No Format
$ setjdk 1.5
Setting this terminal's JDK to 1.5 ... java version "1.5.0_05"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_05-83)
Java HotSpot(TM) Client VM (build 1.5.0_05-48, mixed mode, sharing)
No Format
$ defaultjdk 1.5
Setting default JDK & HotSpot to 1.5 ... Password:
Done.

The script

Add this directly to your .bash_profile or put it in another file and source it from there.

Code Block
#!/bin/bash

function defaultjdk {
    local vmdir=/System/Library/Frameworks/JavaVM.framework/Versions
    local ver=${1?Usage: defaultjdk <version>}

    [ -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 <version>}

    [ -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