bash 如果命令输出包含某个字符串,我如何测试(在一行中)?

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

How do I test (in one line) if command output contains a certain string?

bash

提问by Dane O'Connor

In one line of bash, how do I return an exit status of 0 when the output of /usr/local/bin/monit --versiondoesn't contain exactly 5.5and an exit status of 1 when it does?

在一行 bash 中,当输出/usr/local/bin/monit --version不完全包含时如何返回退出状态为 0,而在包含时返回5.5退出状态为 1?

回答by ruakh

! /usr/local/bin/monit --version | grep -q 5.5

(grepreturns an exit-status of 0 if it finds a match, and 1 otherwise. The -qoption, "quiet", tells it not to print any match it finds; in other words, it tells grepthat the only thing you want is its return-value. The !at the beginning inverts the exit-status of the whole pipeline.)

grep如果找到匹配,则返回退出状态 0,否则返回 1。-q选项“quiet”告诉它不打印它找到的任何匹配;换句话说,它告诉grep你唯一想要的是它的返回-value.!开头反转整个管道的退出状态。)

Edited to add:Alternatively, if you want to do this in "pure Bash" (rather than calling grep), you can write:

编辑添加:或者,如果您想在“纯 Bash”(而不是调用grep)中执行此操作,您可以编写:

[[ $(/usr/local/bin/monit --version) != *5.5* ]]

([[...]]is explained in §3.2.4.2 "Conditional Constructs" of the Bash Reference Manual. *5.5*is just like in fileglobs: zero or more characters, plus 5.5, plus zero or more characters.)

Bash 参考手册的第 3.2.4.2 节“条件构造”中进行了[[...]]解释。就像在 fileglobs 中一样:零个或多个字符,加上,加上零个或多个字符。)*5.5*5.5

回答by perreal

[ $(/usr/local/bin/monit --version) == "5.5" ] 

eg-1: check for success

eg-1:检查是否成功

[ $(/usr/local/bin/monit --version) == "5.5" ] && echo "OK"

eg-2: check for failure

eg-2:检查失败

    [ $(/usr/local/bin/monit --version) == "5.5" ] || echo "NOT OK"

or, to just check if the output contains 5.5:

或者,只检查输出是否包含5.5

[[ $(/usr/local/bin/monit --version) =~ "5.5" ]] || echo "NOT OK"

回答by Matzy

Test the return value of grep:

测试grep的返回值:

sudo service xyz status | grep 'not' &> /dev/null
if [ $? == 0 ]; then
   echo "whateveryouwant"
fi

I would recommend cron, it works fine with SALT stack

我会推荐 cron,它适用于 SALT 堆栈