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
I want to be able to say: If we have Java 11 – do this, if we have Java 17 – do that. Anything else – you can’t have anything else. Please advise
Kate, your question is more about shell programming. You can try “help if” to get some info about the “if-elif-else-fi” shell built-in.
I tested the following and it should work for your purpose:
In Java 9+, a new version string scheme was implemented. Major versions no longer have a leading “1.”, like in “1.7”, “1.8”. I updated the blog post to work for the old and new pattern.
Thanks to Carlos Saltos for suggesting the fix!
See this JEP that describes the changes in detail: https://openjdk.java.net/jeps/223
Also this Oracle page for Java 11: https://docs.oracle.com/en/java/javase/11/install/version-string-format.html
One that works with java 8 and java 11 ->
java -version 2>&1 | head -1 | cut -d'”‘ -f2 | sed ‘/^1\./s///’ | cut -d’.’ -f1
I see that your sed cuts off the leading “1.” when necessary (1.7, 1.8, etc), but leaves the new format that starts with the major version like “11” as is. That’s a nice improvement that works for older and newer Java versions. Thanks for sharing!