Search code examples
linuxparsingversion

How to fetch Java version using single line command in Linux


I want to fetch the Java version in Linux in a single command.

I am new to awk so I am trying something like

java -version|awk '{print$3}'  

But that does not return the version. How would I fetch the 1.6.0_21 from the below Java version output?

java version "1.6.0_21"
Java(TM) SE Runtime Environment (build 1.6.0_21-b06)
Java HotSpot(TM) 64-Bit Server VM (build 17.0-b16, mixed mode)

Solution

    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}'