118

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.

phunehehe
  • 20,240
jackass27
  • 1,183

3 Answers3

145

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
Wildcard
  • 36,499
slm
  • 369,824
  • Here is the document from my linux: Normally the exit status is 0 if a line is selected, 1 if no lines were selected, and 2 if an error occurred. However, if the -q or --quiet or --silent is used and a line is selected, the exit status is 0 even if an error occurred. So there is a subtle difference between using -q and > /dev/null – Kemin Zhou Aug 07 '21 at 17:59
8

Just redirect output of grep to /dev/null:

grep sample test.txt > /dev/null

echo $?
cuonglm
  • 153,898
2

You simply need to combine grep -q <pattern> with an immediate check of the exit code for last process to quit ($?).

You can use this to build up a command like this, for example:

uname -a | grep -qi 'linux' ; case "$?" in "0") echo "match" ;; "1") echo "no match" ;; *) echo "error" ;; esac

You can optionally suppress output from STDERR like so:

grep -qi 'root' /etc/shadow &> /dev/null ; case "$?" in "0") echo "match" ;; "1") echo "no match" ;; *) echo "error: $?" ;; esac

This will print error: 2 from the case statement (assuming we do not have privileges to read /etc/shadow or that the file does not exist) but the error message from grep will be redirected to /dev/null so we don't ever see it.