I use the
init-java-env
script described here to switch between different JDK versions.
After the installation/unpacking of the different JDKs under a common parent folder (e.g.
/use/local/java
), the script bellow can be used to set
JAVA_HOME
and put
JAVA_HOME/bin
in the
PATH
.
Let say you have installed JDK 1.5 and JDK 1.6 at
/usr/local/java/jdk1.5.0_13
and
/use/local/java/jdk1.6.0_03
respectively, than execute the script like this to switch between the JDK versions:
source /usr/local/java/init-java-env jdk1.6
source /usr/local/java/init-java-env jdk1.5
Here comes the script:
#!/bin/bash
#
function get_script_location() {
if [[ "$0" == *"init-java-env" ]]; then
echo
echo " *************************************"
echo " Should be called for sourcing only:"
echo " source $0"
echo " or"
echo " . $0"
echo
exit 1
fi
local script_loc=$(history 1)
if [ -z "$script_loc" ] ; then script_loc="${BASH_SOURCE[0]}" ; fi
script_loc=${script_loc#*. }
script_loc=${script_loc#*source }
script_loc=${script_loc%% }
script_loc=$(eval echo $script_loc)
script_loc=$(readlink -f "$script_loc")
script_loc=$(dirname "$script_loc")
eval "$1=$script_loc"
}
function get_java_home {
local script_dir=""
local java_version=$2
get_script_location script_dir
local _jh=$(find $script_dir -maxdepth 1 -name "*$java_version*" -printf '%p')
if [ -z "$_jh" ]; then
echo "Cannot find Java $java_version under $script_dir"
else
_jh=${_jh/\.\//$(pwd)/}
eval "$1=$_jh"
fi
}
function init_java_env {
local java_version="jdk1.5"
[ $# == 0 ] || java_version="$1"
local java_home_in_path="`which java`"
[ "$java_home_in_path" == "" ] || java_home_in_path="$(dirname $(dirname $java_home_in_path))"
local java_home="$java_home_in_path"
get_java_home java_home $java_version
echo "Found Java at: $java_home"
if [ "$java_home" == "$JAVA_HOME" ] && [ "$java_home" == "$java_home_in_path" ]; then
echo "JAVA_HOME is already set to: $JAVA_HOME"
else
# remove JAVA_HOME/bin from PATH
if [ -n "$JAVA_HOME" ]; then
echo "removing $JAVA_HOME/bin from $PATH"
export PATH=${PATH/$JAVA_HOME\/bin:/}
export PATH=${PATH/$JAVA_HOME\/bin/}
fi
export JAVA_HOME="$java_home"
export PATH=$JAVA_HOME/bin:$PATH
echo "Using Java $JAVA_VERSION at JAVA_HOME: $JAVA_HOME"
fi
}
init_java_env $@
No comments:
Post a Comment