Correct way to check Java version from BASH script
Solution 1:
Perhaps something like:
if type -p java; then
echo found java executable in PATH
_java=java
elif [[ -n "$JAVA_HOME" ]] && [[ -x "$JAVA_HOME/bin/java" ]]; then
echo found java executable in JAVA_HOME
_java="$JAVA_HOME/bin/java"
else
echo "no java"
fi
if [[ "$_java" ]]; then
version=$("$_java" -version 2>&1 | awk -F '"' '/version/ {print $2}')
echo version "$version"
if [[ "$version" > "1.5" ]]; then
echo version is more than 1.5
else
echo version is less than 1.5
fi
fi
Solution 2:
You can obtain java version via:
JAVA_VER=$(java -version 2>&1 | sed -n ';s/.* version "\(.*\)\.\(.*\)\..*".*/\1\2/p;')
it will give you 16
for java like 1.6.0_13
, 15
for version like 1.5.0_17
and 110 for openjdk 11.0.6 2020-01-14 LTS
.
So you can easily compare it in shell:
[ "$JAVA_VER" -ge 15 ] && echo "ok, java is 1.5 or newer" || echo "it's too old..."
UPDATE: This code should work fine with openjdk and JAVA_TOOL_OPTIONS as mentioned in comments.