Home > bash, coding, cygwin, debian, java, linux, mac os > Get java version string via shell commands

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.

The above gets the version from the java command on the PATH.
For other java binaries on your system, use the full path, like:

/full/path/to/some/java -version 2>&1 | head -n 1 | cut -d'"' -f2

To get only the major version part (e.g. 7 for Java 1.7.x), use this:

java -version 2>&1 | head -n 1 | cut -d'"' -f2 | cut -d'.' -f2 

Example: Ensure Java 7 or higher:

#!/bin/bash

version=$(java -version 2>&1 | head -n 1 | cut -d'"' -f2 | cut -d'.' -f2)
if [ $version -lt "7" ]; then
  echo "Java 1.7 or higher is required."
  exit 1
fi
Advertisements
Categories: bash, coding, cygwin, debian, java, linux, mac os Tags: , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: