Skip to content

Instantly share code, notes, and snippets.

@wmono
Last active June 8, 2023 20:18
Show Gist options
  • Save wmono/3b19e6613fb0e8abd798f0644d96c4aa to your computer and use it in GitHub Desktop.
Save wmono/3b19e6613fb0e8abd798f0644d96c4aa to your computer and use it in GitHub Desktop.
This is my JDK switcher script. Assumes bash. You should probably use something like SDKMAN! instead.
#!/bin/bash
# https://gist.github.com/wmono/3b19e6613fb0e8abd798f0644d96c4aa
JDK_PREFIX="${JDK_PREFIX:-$HOME/local}"
###############################################################################
request="$1"
changed_jdk=0
(return 0 2>/dev/null) && was_sourced=1 || was_sourced=0
use_jdk() {
local find_names
build_find_names find_names "$@"
local new_home="$(find "$JDK_PREFIX" -maxdepth 1 -type d,l -a \( "${find_names[@]}" \) 2>/dev/null | sort -n | tail -1)"
if [ -n "$new_home" -a -x "$new_home/bin/java" ]; then
export JAVA_HOME="$new_home"
export PATH="$JAVA_HOME/bin:$PATH"
changed_jdk=1
java -version
else
echo "Cannot find JAVA_HOME for $request in $JDK_PREFIX" >&2
if [ "$was_sourced" -eq 0 ]; then exit 1; fi
fi
}
build_find_names() {
local -n result="$1"
shift
result+=( '-name' "$1" )
shift
while [ -n "$1" ]; do
result+=( '-o' '-name' "$1" )
shift
done
}
case $request in
"")
java -version
if [ "$was_sourced" -eq 0 ]; then exit 1; fi
;;
6|7|8)
use_jdk "jdk${request}u*" "jdk1.${request}.*"
;;
*)
use_jdk "jdk-$request.*"
;;
esac
if [ "$was_sourced" -eq 0 -a "$changed_jdk" -eq 1 ]; then
echo
echo '*** Starting new shell ***'
exec "$SHELL"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment