Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) 
like image 432
AabinGunz Avatar asked Sep 29 '11 11:09

AabinGunz


People also ask

How do I run a Java version from command line?

First, click on the magnifying glass and type “cmd”, then click on the Command Line app icon that appears. Now, enter the command java -version and you'll see the version of Java listed.

How do I change Java version in Linux command line?

/opt/java-selection/openjdk-java-8. bash : This script changes your Java version to OpenJDK Java 8 in your current terminal/shell, and all future terminals and shells.


2 Answers

  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}' 
like image 139
Prince John Wesley Avatar answered Sep 20 '22 15:09

Prince John Wesley


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.

like image 36
Beauness_Round Avatar answered Sep 23 '22 15:09

Beauness_Round