How to Suppress Output from grep and Only Return Exit Status

grepscriptingshell-script

I have the grep command. I'm searching for a keyword from a file, but I don't want to display the match. I just want to know the exit status of the grep.

Best Answer

Any POSIX compliant version of grep has the switch -q for quiet:

-q
     Quiet. Nothing shall be written to the standard output, regardless
     of matching lines. Exit with zero status if an input line is selected.

In GNU grep (and possibly others) you can use long-option synonyms as well:

-q, --quiet, --silent     suppress all normal output

Example

String exists:

$ echo "here" | grep -q "here"
$ echo $?
0

String doesn't exist:

$ echo "here" | grep -q "not here"
$ echo $?
1
Related Question