views:

228

answers:

8

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

+2  A: 
#!/bin/sh

java -version
kek
A: 

Take a look at the output of

java -version
Joey
A: 

You can get the version of the installed JRE using the java command, with the -version switch :

$ java -version
java version "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)
Pascal MARTIN
A: 
P:\>java -version
java version "1.6.0_17"
Java(TM) SE Runtime Environment (build 1.6.0_17-b04)
Java HotSpot(TM) Client VM (build 14.3-b01, mixed mode, sharing)

Use the java -version to bring back the installed JRE version.

(and it looks like I'm outdated, damn!)

Daniel May
+3  A: 

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

monojohnny
lose the head and use awk: java -version 2> print $3 }'
+2  A: 

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

java -version 2>&1 | head -n 1 | cut -d\" -f 2
Grzegorz Oledzki
+1  A: 

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
monojohnny
+1  A: 

just use the shell

$ a=$(java -version 2>&1 >/dev/null)
$ set -- $a
$ echo $3
"1.6.0_0"