bash 检查“cat”的输出是否为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17921816/
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
check if the output of "cat" is not empty
提问by MOHAMED
Is it possible to know if the output of the following command is not empty?
是否可以知道以下命令的输出是否为空?
cat anyfile.txt | grep anymessage
without put the displayed output into a variable and without redirect the displayed output to a file
不将显示的输出放入变量中,也不将显示的输出重定向到文件
回答by Joni
The grep command exits with status 1 if no match was found. You can use the exit status like this:
如果未找到匹配项,grep 命令将以状态 1 退出。您可以像这样使用退出状态:
whatever | grep pattern
echo $?
In a shell script you may even write:
在 shell 脚本中,你甚至可以这样写:
if whatever | grep pattern ; then
# match was found
else
# not found
fi
回答by Phylogenesis
If you do grep 'sometext' anyfile.txt >/dev/null
then nothing will be printed.
如果您这样做,grep 'sometext' anyfile.txt >/dev/null
则不会打印任何内容。
However, if you read $?
after, it will show 0 if it matched lines and 1 otherwise.
但是,如果您$?
稍后阅读,如果匹配行,它将显示 0,否则显示 1。
回答by to4dy
You could write a small script with an if statement and print out true or false.
您可以使用 if 语句编写一个小脚本并打印出 true 或 false。
回答by choroba
You can tell grep -q
to be quiet:
你可以告诉 grep-q
保持安静:
if grep -q anymessage anyfile.txt ; then
# found
else
# not found
fi
回答by user2599522
also "grep -c anymessage anyfile.txt" can be used (-c gets the count of matches)
也可以使用“grep -c anymessage anyfile.txt”(-c 获取匹配数)