Automatically Setting JAVA_HOME to latest JDK version

I need to set the JAVA_HOME to the latest JDK version which is present in the 64_bit folder. Currently, I am setting this to : export JAVA_HOME=/opt/java/hotspot/8/64_bit/jdk1.8.0_172

So is there any way it is automatically picked up the latest JDK version because every time I need to change the script when a new version comes.

Thanks

728x90

1 Answers Automatically Setting JAVA_HOME to latest JDK version

It can be done in a couple of lines of shell script. There are probably a myriad ways to implement this. The following code relies on sort's -V flag to find the latest version.

#!/bin/sh
BASE_DIR=/opt/java/hotspot/8/64_bit/

version=$(ls $BASE_DIR | grep -Eo "([0-9]+\.?){3}(_[0-9]+)?" | sort -Vr | head -1)

if [ -n "$version" ]; then
  folder=$(find $BASE_DIR -maxdepth 1 -name "*${version}*")
  echo "Setting JAVA_HOME to $folder."
  JAVA_HOME="$folder"
  export JAVA_HOME
else
  echo 1>&2 "No JDK installation found in ${BASE_DIR}!"
  exit 1
fi

9 months ago