public
Last active — forked from nicksieger/pickjdk.sh

JDK picker for OS X.

  • Download Gist
pickjdk.sh
Shell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
#!/bin/bash
#
# Provides a function that allows you to choose a JDK. Just set the environment
# variable JDKS_ROOT to the directory containing multiple versions of the JDK
# and the function will prompt you to select one. JAVA_HOME and PATH will be cleaned
# up and set appropriately.
 
# Usage:
# Include in .profile or .bashrc or source at login to get 'pickjdk' command.
# 'pickjdk' alone to bring up a menu of installed JDKs on OS X. Select one.
# 'pickjdk <jdk number>' to immediately switch to one of those JDKs.
 
_macosx()
{
if [ $(uname -s) = Darwin ]; then
return 0
else
return 1
fi
}
 
JDKS_ROOT=
if _macosx; then
JDKS_ROOT=/Library/Java/JavaVirtualMachines
fi
 
pickjdk()
{
if [ -z "$JDKS_ROOT" ]; then
return 1
fi
 
declare -a JDKS
local n=1 jdk total_jdks choice=0 currjdk=$JAVA_HOME explicit_jdk
for jdk in $JDKS_ROOT/[0-9a-z]*; do
if [ -e $jdk ]; then
JDKNAMES[$n]="$(basename $jdk)"
if _macosx; then
jdk=$jdk/Contents/Home
fi
if [ -z "$1" ]; then
echo -n " $n) ${JDKNAMES[$n]}"
if [ $jdk = "$currjdk" ]; then
echo " < CURRENT"
else
echo
fi
fi
JDKS[$n]=$jdk
total_jdks=$n
n=$[ $n + 1 ]
fi
done
if [ -z "$1" ]; then
echo " $n) None"
fi
JDKS[$n]=None
total_jdks=$n
 
if [ $total_jdks -gt 1 ]; then
if [ -z "$1" ]; then
while [ -z "${JDKS[$choice]}" ]; do
echo -n "Choose one of the above [1-$total_jdks]: "
read choice
done
else
choice=$1
fi
fi
 
if [ -z "$currjdk" ]; then
currjdk=$(dirname $(dirname $(type -path java)))
fi
 
if [ ${JDKS[$choice]} != None ]; then
export JAVA_HOME=${JDKS[$choice]}
else
unset JAVA_HOME
fi
 
explicit_jdk=
for jdk in ${JDKS[*]}; do
if [ "$currjdk" = "$jdk" ]; then
explicit_jdk=$jdk
break
fi
done
 
if [ "$explicit_jdk" ]; then
if [ -z "$JAVA_HOME" ]; then
PATH=$(echo $PATH | sed "s|$explicit_jdk/bin:*||g")
else
PATH=$(echo $PATH | sed "s|$explicit_jdk|$JAVA_HOME|g")
fi
elif [ "$JAVA_HOME" ]; then
PATH="$JAVA_HOME/bin:$PATH"
fi
 
echo "New JDK: ${JDKNAMES[$choice]}"
 
hash -r
unset JDKS
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.