How to fetch Java version using single line comman

2019-03-08 15:02发布

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)

6条回答
对你真心纯属浪费
2楼-- · 2019-03-08 15:39
  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}'
    
查看更多
3楼-- · 2019-03-08 15:39

This way works for me.

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

1.8.0_171
查看更多
Rolldiameter
4楼-- · 2019-03-08 15:45

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.

查看更多
Anthone
5楼-- · 2019-03-08 15:46

Getting only the "major" build #:

java -version 2>&1 | head -n 1 | awk -F'["_.]' '{print $3}'
查看更多
Melony?
6楼-- · 2019-03-08 15:48

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"
~
查看更多
冷血范
7楼-- · 2019-03-08 15:55

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
查看更多
登录 后发表回答