简体   繁体   中英

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

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.

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

Since (at least on my linux system) the version string looks like "1.8.0_45":

 #!/bin/bash
 function checkJavaVers {
    for token in $(java -version 2>&1)
    do
        if [[ $token =~ \"([[:digit:]])\.([[:digit:]])\.(.*)\" ]]
        then
            export JAVA_MAJOR=${BASH_REMATCH[1]}
            export JAVA_MINOR=${BASH_REMATCH[2]}
            export JAVA_BUILD=${BASH_REMATCH[3]}
            return 0
        fi
    done
    return 1
}

#test
checkJavaVers || { echo "check failed" ; exit; }
echo "$JAVA_MAJOR $JAVA_MINOR $JAVA_BUILD"
~

You can use --version and in that case it's not required to redirect to stdout

java --version | head -1 | cut -f2 -d' '

From java help

-version      print product version to the error stream and exit
--version     print product version to the output stream and exit

只获得“主要”构建#:

java -version 2>&1 | head -n 1 | awk -F'["_.]' '{print $3}'

This way works for me.

# java -version 2>&1|awk '/version/ {gsub("\"","") ; print $NF}'

1.8.0_171

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM