You may use the script below.
You should configure the path for java "/bin" directory and a number for each version according to your system.
#!/bin/bash
# update-java script
# Supported versions from the script. You may add more version numbers according to your needs.
supported_versions=( 8 11 )
# Validate that an argument has been given
if [ -z "$1" ]; then
echo -e "No argument given. You should set as first argument the preferred java version.\nAvailable values: ${supported_versions[@]}"
exit
fi
# Java "/bin" of each version. Be careful, each path should have the same index with the supported_versions array.
version_path=( "/usr/lib/jvm/jdk1.8.0_171/bin" "/usr/lib/jvm/java-11-openjdk-amd64/bin")
# Configure the alternatives
found=0
for i in "${!supported_versions[@]}"; do
if [[ ${supported_versions[$i]} -eq $1 ]]; then
update-alternatives --set java ${version_path[$i]}/java
update-alternatives --set javac ${version_path[$i]}/javac
found=1
fi
done
# If a wrong version number has been given
if [ $found -ne 1 ]; then
echo "You didn't provide a version of: ${supported_versions[@]}"
fi
If you save the script with name "update-java", then set the executable permission, you will be able to run like below.
$sudo update-java 12
You didn't provide a version of: 8 11
$sudo update-java
No argument given. You should set as first argument the preferred java version.
Available values: 8 11
$sudo update-java 11