Correct way to check Java version from BASH script Correct way to check Java version from BASH script java java

Correct way to check Java version from BASH script


Perhaps something like:

if type -p java; then    echo found java executable in PATH    _java=javaelif [[ -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"fiif [[ "$_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    fifi


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.


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