beta.blog

Archive for June, 2025

Java: Get major java version via command line

by on Jun.01, 2025, under News

Getting the major Java version in say a bash script isn’t always quite trivial. It seems like there isn’t a built‐in switch in the Java launcher that prints only the major version (as a clean number) to be reused in a shell script. Thus, we’d typically need to parse the output of the regular version command.

java -version 2>&1 | awk -F '"' '/version/ {print $2}' | awk -F. '{print ($1=="1" ? $2 : $1)}'

This command uses the regular version switch to get the well known output:

# java -version
openjdk version "22.0.2" 2024-07-16
OpenJDK Runtime Environment Corretto-22.0.2.9.1 (build 22.0.2+9-FR)
OpenJDK 64-Bit Server VM Corretto-22.0.2.9.1 (build 22.0.2+9-FR, mixed mode, sharing)

  • The first awk extracts the quoted version string
  • In the second awk we decided if the version starts with a 1. (like in older Java versions such as 8) or the first field for later versions.

This approach makes it easier to integrate the version number into scripts.

Leave a Comment more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!