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

137,697

Solution 1

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

Solution 2

Just redirect output of grep to /dev/null:

grep sample test.txt > /dev/null

echo $?

Solution 3

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.

Share:
137,697

Related videos on Youtube

jackass27
Author by

jackass27

Updated on September 18, 2022

Comments

  • jackass27
    jackass27 almost 2 years

    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.

  • WinnieNicklaus
    WinnieNicklaus over 10 years
    This will fail to echo $? if grep returns a non-zero exit code.
  • Kemin Zhou
    Kemin Zhou almost 3 years
    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