How can I suppress output from grep, so that it only returns the exit status?

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

Just redirect output of grep to /dev/null:

grep sample test.txt > /dev/null

echo $?

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.