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