Correct way to check Java version from BASH script
The answers above work correctly only for specific Java versions (usually for the ones before Java 9 or for the ones after Java 8.
I wrote a simple one liner that will return an integer for Java versions 6 through 11 (and possibly all future versions, until they change it again!).
It basically drops the "1." at the beginning of the version number, if it exists, and then considers only the first number before the next ".".
java -version 2>&1 | head -1 | cut -d'"' -f2 | sed '/^1\./s///' | cut -d'.' -f1
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.
You can issue java -version
and read & parse the output
java -version 2>&1 >/dev/null | grep 'java version' | awk '{print $3}'
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