how to write shell script to get JRE version

10,224

Solution 1

If you want just the version (rather than the whole string), you can do something like:

-- Save this as (say) javaversion.sh

#!/bin/sh
# Changed code to remove the 'head -1' as per the suggestion in comment.
JAVA_VERSION=`java -version 2>&1 |awk 'NR==1{ gsub(/"/,""); print $3 }'`
# export JAVA_VERSION
echo $JAVA_VERSION

This gives:

$ 1.6.0_15

On my system (damn it, even more out of date !! :-) )

I found '2>&1' necessary on my system, since the output seems to go to 'stderr' rather than 'stdout'. (2>&1 = send the output of standard error to the standard out stream; in this case so we can go ahead and process with the head etc...).

The 'gsub' bit in the awk is necessary to remove the double-quotes in the string. (Global SUBstitue), $3 is the third field (awk defaults its field separator to white-space).

The "backticks" ( ` ) are used so we can capture the output - and then we store it on a variable.

[ Using 'cut' rather than 'awk' might be more elegant here - see GrzegorzOledzki's post.]

Solution 2

Following the idea behind monojohnny's answer, but using cut instead of awk:

java -version 2>&1 | head -n 1 | cut -d\" -f 2

Solution 3

Alternatively:

Write a Java class that accesses System Property "java.version": which will strip out some of the other formatting crap out of there and allow you to output to standard out rather than standard error.

Just have your shell script call it with a

java -cp <classpath> GetJavaVersion.class

Solution 4

#!/bin/sh

java -version

Solution 5

just use the shell

$ a=$(java -version 2>&1 >/dev/null)
$ set -- $a
$ echo $3
"1.6.0_0"
Share:
10,224
Sunil Kumar Sahoo
Author by

Sunil Kumar Sahoo

Please have a look on my career2.0 profile to know more about me. For source code follow me on github For articles follow me on Medium Thanks Sunil Kumar Sahoo Email Address [email protected]

Updated on June 05, 2022

Comments

  • Sunil Kumar Sahoo
    Sunil Kumar Sahoo almost 2 years

    Hi I want to write a shell scripting which will return the installed JRE version. How to write shell script file to achieve the above.

    If I write java -version then the application returns "1.6.0_14" Java(TM) SE Runtime Environment (build 1.6.0_14-b08) Java HotSpot(TM) Server VM (build 14.0-b16, mixed mode)".

    But I donot want any string. I want only jre version.

    thanks Sunil Kumar Sahoo

  • ghostdog74
    ghostdog74 over 14 years
    lose the head and use awk: java -version 2>&1 |awk 'NR==1{ gsub(/"/,""); print $3 }'
  • Michael
    Michael over 12 years
    @monojohnny is it possible to just print it on the screen from shell without executing a script ?
  • kevingreen
    kevingreen over 11 years
    @Michael you mean other than just using " java -version" ?