检查 Java 是否与 Bash 一起安装

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36388348/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 14:27:46  来源:igfitidea点击:

Check if Java Installed with Bash

javabash

提问by WASasquatch

Can someone tell me why this simple command cannot find the output "java version"?

有人能告诉我为什么这个简单的命令找不到输出“java 版本”吗?

if java -version | grep -q "java version" ; then
  echo "Java installed."
else
  echo "Java NOT installed!"
fi

output from java -versionis as follows

输出java -version如下

java version "1.8.0_77"
Java(TM) SE Runtime Environment (build 1.8.0_77-b03)
Java HotSpot(TM) 64-Bit Server VM (build 25.77-b03, mixed mode)

回答by Reimeus

javaoutputs to STDERR. You can use

java输出到 STDERR。您可以使用

if java -version 2>&1 >/dev/null | grep -q "java version" ; then

but probably simpler to do something like

但可能更简单地做类似的事情

if [ -n `which java` ]; then

回答by chitresh

If your java is openJDK then you can use following options

如果您的 java 是 openJDK,那么您可以使用以下选项

java -version 2>&1 >/dev/null | grep "java version\|openjdk version"

or you can make more generic by

或者你可以通过

java -version 2>&1 >/dev/null | egrep "\S+\s+version"

to get java version

获取java版本

JAVA_VER=$(java -version 2>&1 >/dev/null | egrep "\S+\s+version" | awk '{print }' | tr -d '"')