jsarbour
jsarbour

Reputation: 1158

What is the point of "grep -q"

I was reading the grep manual 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 whose raison d'être 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?

Upvotes: 60

Views: 69729

Answers (2)

Kim
Kim

Reputation: 1660

Here's an example of grep -q: scanning the output of a command for a particular value, then performing an action if the value is found:

if docker context ls | grep -q dm-manager; then
  docker context rm dm-manager
fi

If the list of docker contexts contains dm-manager then remove docker context dm-manager.

Upvotes: 4

chepner
chepner

Reputation: 531868

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

Upvotes: 82

Related Questions