Answers:
的任何POSIX兼容版本都grep具有-q用于静音的开关:
-q
     Quiet. Nothing shall be written to the standard output, regardless
     of matching lines. Exit with zero status if an input line is selected.在GNU grep(可能还有其他的grep)中,您也可以使用长选项同义词:
-q, --quiet, --silent     suppress all normal output字符串存在:
$ echo "here" | grep -q "here"
$ echo $?
0字符串不存在:
$ echo "here" | grep -q "not here"
$ echo $?
1您只需要grep -q <pattern>与退出代码的立即检查结合起来,最后退出的进程($?)。
您可以使用它来构建这样的命令,例如:
uname -a | grep -qi 'linux' ;  case "$?" in "0") echo "match" ;; "1") echo "no match" ;; *) echo "error" ;; esac
您可以选择抑制STDERR类似的输出:
grep -qi 'root' /etc/shadow &> /dev/null ;  case "$?" in "0") echo "match" ;; "1") echo "no match" ;; *) echo "error: $?" ;; esac
这将从语句中打印error: 2出来case(假设我们没有读取权限/etc/shadow或该文件不存在),但错误消息from grep将被重定向到,/dev/null因此我们永远不会看到它。
echo $?如果grep返回非零退出代码,将失败。