bash 检查命令的输出是否包含 shell 脚本中的某个字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16931244/
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
Checking if output of a command contains a certain string in a shell script
提问by user1118764
I'm writing a shell script, and I'm trying to check if the output of a command contains a certain string. I'm thinking I probably have to use grep, but I'm not sure how. Does anyone know?
我正在编写一个 shell 脚本,我正在尝试检查命令的输出是否包含某个字符串。我想我可能必须使用 grep,但我不确定如何使用。有人知道吗?
采纳答案by perreal
Test the return value of grep:
测试grep的返回值:
./somecommand | grep 'string' &> /dev/null
if [ $? == 0 ]; then
echo "matched"
fi
which is done idiomatically like so:
这是惯用的方式:
if ./somecommand | grep -q 'string'; then
echo "matched"
fi
and also:
并且:
./somecommand | grep -q 'string' && echo 'matched'
回答by mat
Testing $?
is an anti-pattern
测试$?
是一种反模式
if ./somecommand |?grep -q 'string'; then
echo "matched"
fi
回答by Noam Manos
Another option is to check for regular expression match on the command output.
另一种选择是检查命令输出上的正则表达式匹配。
For example:
例如:
[[ "$(./somecommand)" =~ "sub string" ]] && echo "Output includes 'sub string'"
回答by Ehsan Barkhordar
A clean if/else conditional shell script:
一个干净的 if/else 条件 shell 脚本:
if ./somecommand | grep -q 'some_string'; then
echo "exists"
else
echo "doesn't exist"
fi