Skip to content

Instantly share code, notes, and snippets.

@duydao
Last active September 4, 2016 22:46
Show Gist options
  • Save duydao/9950734 to your computer and use it in GitHub Desktop.
Save duydao/9950734 to your computer and use it in GitHub Desktop.
java_home wrapper for Mac OS X, adding support for jenv

java_home wrapper for Mac OS X, adding support for jenv

this script checks if a (global) version was set by jenv. if so, use that path if no version was requested explicitly (e.g. by java_home -v '1.7.*' or something)

# set env if not already done so. something like this for bash
echo "export JAVA_HOME=`/usr/libexec/java_home`" >> ~/.bash_profile;

# this should be brew install something, but for now...
curl 'https://gist.githubusercontent.com/duydao/9950734/raw/dff4d3bde816bfc0e9e11c4498a68c43800ae090/java_home' -o /usr/local/bin/java_home
chmod +x /usr/local/bin/java_home

# /usr/libexec is owned by root, so we have to sudo
sudo mv /usr/libexec/java_home /usr/libexec/java_home_orig
sudo ln -s /usr/local/bin/java_home /usr/libexec/java_home

# restart console or source ~/.bash_profile

#!/usr/bin/env bash
ORIG=/System/Library/Frameworks/JavaVM.framework/Versions/Current/Commands/java_home
if [ -z "$JENV_ROOT" ]; then
JENV_ROOT=~/.jenv
fi
if [ -f "$JENV_ROOT/version" ]; then
CURRENT_VERSION=`/bin/cat $JENV_ROOT/version`
fi
if [ -z "$CURRENT_VERSION" ]; then
exec $ORIG $@
fi
PATH="$JENV_ROOT/versions/$CURRENT_VERSION"
args=$@
while [ "$1" != "" ]; do
case $1 in
-a | --arch)
shift
arg_arch=$1
;;
-d | --datamodel)
shift
arg_datamodel=$1
;;
-v | --version)
shift
arg_version=$1
;;
-V | --verbose)
arg_verbose=1
;;
*)
break
;;
esac
shift
done
# reset args
set -- $args
# read version from jenv if no version was explicitly set
if [ -z "$arg_version" ]; then
# no explicit version was set, use jenv
# strip platform and arch from: oracle64-1.7.0_51
v=${CURRENT_VERSION#*-}
if [ -n "${v}" ]; then
VERSION="$v"
fi
fi
# wrap only if empty, arch or datamodel...
if [ $# -gt 0 ]; then
if [ -n "$arg_arch" ] || [ -n "$arg_datamodel" ]; then
if [ -z "$arg_version" ] && [ -n "$VERSION" ]; then
exec $ORIG -v $VERSION "$@"
else
exec $ORIG "$@"
fi
else
exec $ORIG "$@"
fi
elif [ -d "$PATH" ]; then
cd $PATH
pwd -P
elif [ -f "$ORIG" ]; then
exec $ORIG
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment