如何在 Linux 中使用单行命令获取 Java 版本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7596454/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to fetch Java version using single line command in Linux
提问by AabinGunz
I want to fetch the Java version in Linux in a single command.
我想在单个命令中获取 Linux 中的 Java 版本。
I am new to awk so I am trying something like
我是 awk 的新手,所以我正在尝试类似的东西
java -version|awk '{print}'
But that does not return the version. How would I fetch the 1.6.0_21
from the below Java version output?
但这不会返回版本。我将如何1.6.0_21
从下面的 Java 版本输出中获取?
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)
采纳答案by Prince John Wesley
- Redirect stderr to stdout.
- Get first line
Filter the version number.
java -version 2>&1 | head -n 1 | awk -F '"' '{print }'
- 将 stderr 重定向到 stdout。
- 获取第一行
过滤版本号。
java -version 2>&1 | head -n 1 | awk -F '"' '{print }'
回答by Beauness_Round
This is a slight variation, but PJW's solution didn't quite work for me:
这是一个细微的变化,但 PJW 的解决方案对我来说不太适用:
java -version 2>&1 | head -n 1 | cut -d'"' -f2
just cut the string on the delimiter "
(double quotes) and get the second field.
只需剪切分隔符"
(双引号)上的字符串并获取第二个字段。
回答by Timothy Aanerud
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.
我建议使用grep -i version
以确保您获得包含版本字符串的正确行。如果您设置了环境变量 JAVA_OPTIONS,openjdk 将在打印版本信息之前打印 java 选项。此版本返回 1.6、1.7 等。
java -version 2>&1 | grep -i version | cut -d'"' -f2 | cut -d'.' -f1-2
回答by gerardw
Since (at least on my linux system) the version string looks like "1.8.0_45":
因为(至少在我的 linux 系统上)版本字符串看起来像“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"
~
回答by bentzy
Getting only the "major" build #:
只获取“主要”构建#:
java -version 2>&1 | head -n 1 | awk -F'["_.]' '{print }'
回答by Shirish Shukla
This way works for me.
这种方式对我有用。
# java -version 2>&1|awk '/version/ {gsub("\"","") ; print $NF}'
1.8.0_171
回答by Oo.oO
You can use --version
and in that case it's not required to redirect to stdout
您可以使用--version
,在这种情况下不需要重定向到标准输出
java --version | head -1 | cut -f2 -d' '
From java help
来自java帮助
-version print product version to the error stream and exit
--version print product version to the output stream and exit