Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to write shell script to get JRE version

Tags:

java

shell

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

like image 921
Sunil Kumar Sahoo Avatar asked Apr 12 '26 03:04

Sunil Kumar Sahoo


2 Answers

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

java -version 2>&1 | head -n 1 | cut -d\" -f 2
like image 150
Grzegorz Oledzki Avatar answered Apr 14 '26 15:04

Grzegorz Oledzki


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

like image 28
3 revsmonojohnny Avatar answered Apr 14 '26 16:04

3 revsmonojohnny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!