Get java version string via shell commands

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

5 thoughts on “Get java version string via shell commands

  1. 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

    1. 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:

      if [ -z "$version" ]; then
        echo "version is undefined"
      elif [ "$version" = "11" ]; then
        echo "Java 11"
      elif [ "$version" = "17" ]; then
        echo "Java 17"
      else
        echo "Unsupported version: $version"
      fi
      
  2. One that works with java 8 and java 11 ->

    java -version 2>&1 | head -1 | cut -d'”‘ -f2 | sed ‘/^1\./s///’ | cut -d’.’ -f1

    1. 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!

Leave a reply to oldo Cancel reply