Last active
August 8, 2022 07:59
-
-
Save elementbound/2bb3bddc59e81fba39c158558294c8d0 to your computer and use it in GitHub Desktop.
Switch Java versions from Git Bash
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Return PATH without directory | |
# | |
# @param dir directory to remove | |
function rmpath() { | |
dir="$1" | |
result="" | |
while read -r dir; do | |
if [ "$dir" != "$1" ]; then | |
result="$result:$dir" | |
fi | |
done <<< "$(echo $PATH | tr ":" "\n")"; | |
echo "$result" | sed 's/^://' | |
} | |
# Return PATH with directory appended | |
# | |
# @param dir directory to add | |
function addpath() { | |
echo "$PATH:$1" | |
} | |
# Add specified Java version to PATH. | |
# This command will remove any currently registered Java versions. | |
# | |
# @param version version to use | |
function useJava() { | |
declare -A JAVA_DIRECTORIES | |
## !!CUSTOMIZE!! this part with your own paths | |
JAVA_DIRECTORIES=( | |
["8"]="/c/Program Files/Java/jdk1.8.0_221" | |
["9"]="/c/Program Files/Java/jdk-9.0.4" | |
["12"]="/c/Program Files/OpenJDK/jdk-12.0.2" | |
) | |
if [ -z "${JAVA_DIRECTORIES[$1]}" ]; then | |
echo "Unknown Java version: $1" | |
return 1 | |
fi; | |
if where java >/dev/null 2>&1; then | |
echo "Removing Java from PATH" | |
while read -r javadir; do | |
javadir="$(dirname "$javadir")" | |
javadir="$(echo $javadir | sed 's/\\/\//g' | sed 's/^\(.*\):/\/\l\1/')" | |
echo "Removing $javadir" | |
PATH="$(rmpath "$javadir")" | |
done <<< "$(where java)"; | |
fi; | |
echo "Adding Java $1 to PATH"; | |
PATH="$(addpath "${JAVA_DIRECTORIES[$1]}/bin")" | |
export JAVA_HOME="${JAVA_DIRECTORIES[$1]}" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment