“ grep -q”的意义是什么?

jsa*_*our 4 linux bash grep gnu

I was reading the grep man page and came across the -q option, which tells grep to "not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected."

I don't understand why this could be desirable or useful behavior. In a program who's reason d'etre seems to be read from stdin, process, write to stdout, why would I want to silence it completely?

In what case would silencing a program whose goal it is to output things be useful? Why would someone want to entirely ignore errors and force a successful return code?

Thanks!

che*_*ner 6

的退出状态grep不一定表示有错误  ;它指示成功或失败。grep将成功定义为匹配1条或更多行。失败包括零行匹配,或其他一些错误,这些错误首先导致无法进行匹配。

-q当您不关心匹配的行时,仅使用某些匹配的行时使用。

if grep -q foo file.txt; then
    echo "file.txt contains foo"
else
    echo "file.txt does not contain foo"
fi
Run Code Online (Sandbox Code Playgroud)

  • 因为退出状态不同,这就是 if 所看的。 (6认同)
  • 不确定“作为函数”是什么意思,但在所示的示例中,您对看到包含单词“foo”的行不感兴趣,只对知道它们存在感兴趣。 (2认同)