Skip to content

Instantly share code, notes, and snippets.

@kparmar1
Forked from tobias/setjdk.fish
Last active March 5, 2022 12:04
Show Gist options
  • Save kparmar1/9dbe7bfcb46d71393d4d59607a747b5b to your computer and use it in GitHub Desktop.
Save kparmar1/9dbe7bfcb46d71393d4d59607a747b5b to your computer and use it in GitHub Desktop.
Manage multiple java versions on the mac from the fish shell
function setjdk
if test -n "$JAVA_HOME"
removeFromPath "$JAVA_HOME/bin"
end
if test "$argv[1]" = "-t"
set -l POSSIBLE_JAVA_HOME (/usr/libexec/java_home -V 2>&1 >/dev/null | grep $argv[2] | awk -F '\t' '{print $3}')
if test -d "$POSSIBLE_JAVA_HOME"
set -gx JAVA_HOME $POSSIBLE_JAVA_HOME
set -gx PATH $JAVA_HOME/bin $PATH
else
echo "Unable to find any JVMs matching version \""$argv[2]"\"."
end
else
set -gx JAVA_HOME (/usr/libexec/java_home -v $argv[1])
set -gx PATH $JAVA_HOME/bin $PATH
end
end
function removeFromPath
set -l idx 0
for x in (seq (count $PATH))
if test "$argv[1]" = "$PATH[$x]"
set idx $x
end
end
if test $idx -gt 0
set -e PATH[$idx]
end
end
@kparmar1
Copy link
Author

kparmar1 commented Mar 5, 2022

USAGE:

The output of the command gives you the parameter you supply to the script:
/usr/libexec/java_home -V

Will output the JDK version for you to select:

Matching Java Virtual Machines (7):
17.0.2, x86_64: "OpenJDK 17.0.2" /Library/Java/JavaVirtualMachines/Openjdk-17.0.2.jdk/Contents/Home
17.0.2, x86_64: "Java SE 17.0.2" /Library/Java/JavaVirtualMachines/jdk-17.0.2.jdk/Contents/Home
16, x86_64: "Java SE 16" /Library/Java/JavaVirtualMachines/jdk-16.jdk/Contents/Home
15.0.1, x86_64: "Java SE 15.0.1" /Library/Java/JavaVirtualMachines/jdk-15.0.1.jdk/Contents/Home
14.0.1, x86_64: "Java SE 14.0.1" /Library/Java/JavaVirtualMachines/jdk-14.0.1.jdk/Contents/Home
11.0.10, x86_64: "Java SE 11.0.10" /Library/Java/JavaVirtualMachines/jdk-11.0.10.jdk/Contents/Home
1.8.0_251, x86_64: "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_251.jdk/Contents/Home

Currently you supply the first version text to select the JDK you want to use (or matching).

setjdk 17.0.2

The script has been enhanced to work with the text description, the reason being that you can have multiple same versions from different vendors, so how do you select which version of 17.0.2 you would like? Therefore the script now accepts an option (-t) allowing you supply the text description:

setjdk -t "OpenJDK 17.0.2"

or say

setjdk -t "Java SE 17.0.2"

Now you will get the exact version/vendor JDK. So the script operates as previously but with additional flag -t if required.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment