如何抑制 grep 的输出,使其仅返回退出状态?

jac*_*s27 88 grep scripting shell-script

我有grep命令。我正在从文件中搜索关键字,但我不想显示匹配项。我只想知道grep.

slm*_*slm 113

任何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.
Run Code Online (Sandbox Code Playgroud)

在 GNU grep(可能还有其他)中,您也可以使用长选项同义词:

-q, --quiet, --silent     suppress all normal output
Run Code Online (Sandbox Code Playgroud)

例子

字符串存在:

$ echo "here" | grep -q "here"
$ echo $?
0
Run Code Online (Sandbox Code Playgroud)

字符串不存在:

$ echo "here" | grep -q "not here"
$ echo $?
1
Run Code Online (Sandbox Code Playgroud)


cuo*_*glm 6

只需将输出重定向grep/dev/null

grep sample test.txt > /dev/null

echo $?
Run Code Online (Sandbox Code Playgroud)

  • 如果`grep` 返回一个非零退出代码,这将无法`echo $?`。 (2认同)