javabashjshell

How to output the Java runtime version in one line to the shell?


Let's say I want to get the content of java.runtime.version to the Linux shell.

I don't want to call java -version and or doing any kind of grepping / sedding as we used this approach already in the past and it proved to be flaky.

➜  java -version
openjdk version "21" 2023-09-19 LTS
OpenJDK Runtime Environment Temurin-21+35 (build 21+35-LTS)
OpenJDK 64-Bit Server VM Temurin-21+35 (build 21+35-LTS, mixed mode)

This e.g. example contains too much output which changes from release to release and also from vendor to vendor.

What I tried already was using jshell:

But the output still contains all the command feedback which I cannot disable (At least I don't know:

➜  printf $'System.out.println(java.lang.System.getProperty("java.runtime.version"));\n/exit\n' | jshell -s
-> System.out.println(java.lang.System.getProperty("java.runtime.version"))21+35-LTS
-> %

What I want in this example, is only the 21+35-LTS part in a reliable and future proof way.

I am open to use tools available in an Ubuntu slim base image or in the recent Java jdk.

EDIT: I am not opposed to grep/sed in general as long as the solution is half-way future proof and works with different Java vendors.


Solution

  • You can view all system properties with -XshowSettings, so something like this should work:

      java -XshowSettings:properties 2>&1 | grep java.runtime.version