是否有可能知道下面的命令的输出是不是空的?
cat anyfile.txt | grep anymessage
而不会将显示的输出放入一个variables中,而不会将显示的输出redirect到一个文件
如果未找到匹配项,则grep命令将以状态1退出。 你可以像这样使用退出状态:
whatever | grep pattern echo $?
在shell脚本中,你甚至可以写:
if whatever | grep pattern ; then # match was found else # not found fi
如果你grep 'sometext' anyfile.txt >/dev/null
那么什么都不会被打印。
但是,如果你读$?
之后,如果匹配行,则显示0,否则显示1。
你可以写一个if语句的小脚本,并输出true或false。
你可以告诉grep -q
很安静:
if grep -q anymessage anyfile.txt ; then # found else # not found fi
也可以使用“grep -c anymessage anyfile.txt”(-c获取匹配数)