How to fetch Java version using single line command in Linux

This is a slight variation, but PJW's solution didn't quite work for me:

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

just cut the string on the delimiter " (double quotes) and get the second field.


  1. Redirect stderr to stdout.
  2. Get first line
  3. Filter the version number.

    java -version 2>&1 | head -n 1 | awk -F '"' '{print $2}'
    

I'd suggest using grep -i version to make sure you get the right line containing the version string. If you have the environment variable JAVA_OPTIONS set, openjdk will print the java options before printing the version information. This version returns 1.6, 1.7 etc.

java -version 2>&1 | grep -i version | cut -d'"' -f2 | cut -d'.' -f1-2