Determine the pure java version string from any Unix/Linux shell (including Cygwin):
java -version 2>&1 | head -n 1 | cut -d'"' -f2
This requires only the very commonly available and lightweight “head” and “cut” commands.
I originally found the one-liner on stackoverflow. Thanks to the friendly folks who shared it.
To get only the major version part (e.g. 8 for Java 1.8.x, 11 for 11.x), use this:
java -version 2>&1 \
| head -1 \
| cut -d'"' -f2 \
| sed 's/^1\.//' \
| cut -d'.' -f1
Note: The sed step is required for versions up to Java 8 that start with the “1.” prefix.
Example: Ensure Java 11 or higher:
#!/bin/bash
version=$(java -version 2>&1 \
| head -1 \
| cut -d'"' -f2 \
| sed 's/^1\.//' \
| cut -d'.' -f1
)
if [ $version -lt "11" ]; then
echo "Java 11 or higher is required."
exit 1
fi