Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of "grep -q"

Tags:

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!

like image 957
jsarbour Avatar asked May 16 '19 13:05

jsarbour


People also ask

What does '- Q do in grep?

grep defines success as matching 1 or more lines. Failure includes matching zero lines, or some other error that prevented matching from taking place in the first place. -q is used when you don't care about which lines matched, only that some lines matched.

Is grep -' output in Unix?

In Linux and Unix Systems Grep, short for “global regular expression print”, is a command used in searching and matching text files contained in the regular expressions. Furthermore, the command comes pre-installed in every Linux distribution.

What is the difference between grep and Egrep?

The egrep command treats the meta-characters as they are and do not require to be escaped as is the case with grep. This allows reducing the overhead of replacing these characters while pattern matching making egrep faster than grep or fgrep. Options: Most of the options for this command are same as grep.


1 Answers

The exit status of grep doesn't necessarily indicate an error ; it indicates success or failure. grep defines success as matching 1 or more lines. Failure includes matching zero lines, or some other error that prevented matching from taking place in the first place.

-q is used when you don't care about which lines matched, only that some lines matched.

if grep -q foo file.txt; then     echo "file.txt contains foo" else     echo "file.txt does not contain foo" fi 
like image 147
chepner Avatar answered Sep 30 '22 20:09

chepner