我如何测试(一行)命令输出是否包含某个字符串? [英] How do I test (in one line) if command output contains a certain string?

查看:98
本文介绍了我如何测试(一行)命令输出是否包含某个字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

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

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

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

编辑后添加:或者,如果要在纯Bash"中执行此操作(而不是调用grep),则可以编写:

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

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

([[...]]§ 3.2.4.2中进行了解释 Bash参考手册 的条件构造".*5.5*类似于文件组:零个或多个字符,加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.)

这篇关于我如何测试(一行)命令输出是否包含某个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆