Skip to content

Instantly share code, notes, and snippets.

@corneil
Last active January 31, 2024 18:40
Show Gist options
  • Save corneil/8212ede9e6cadf10a4ccef2a73041fc0 to your computer and use it in GitHub Desktop.
Save corneil/8212ede9e6cadf10a4ccef2a73041fc0 to your computer and use it in GitHub Desktop.
Easily select java version and distribution with sdkman
#!/bin/bash
function sdkj() {
if [ "$1" == "" ]; then
echo "Expected Version prefix"
exit 1
fi
PREFIX=$1
CONTAINS=$2
# list candidates in the order they were installed. Last matching installed will be selected.
CANDIDATES=$(ls -tr ~/.sdkman/candidates/java/)
CANDIDATE=
for v in $CANDIDATES; do
if [[ "$v" == *"${PREFIX}."* ]]; then
if [ "$CONTAINS" != "" ]; then
if [[ "$v" == *"${CONTAINS}"* ]]; then
CANDIDATE="$v"
fi
else
CANDIDATE="$v"
fi
fi
done
if [ "$CANDIDATE" != "" ]; then
source "$HOME/.sdkman/bin/sdkman-init.sh"
sdk use java $CANDIDATE
else
echo "Couldn't find an installed distribution for $@"
fi
}
if [ "$1" != "" ]; then
sdkj $@
fi
@corneil
Copy link
Author

corneil commented Nov 28, 2023

Using it is as simple as:
source sdk-java.sh 17
OR
source sdk-java.sh 21 crac
OR
After source sdk-java.sh
sdkj 17
OR
sdkj 21 graal

@corneil
Copy link
Author

corneil commented Jan 31, 2024

Since semantic version don't sort in alphabetical order, updated to select the match that was installed last.

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