0

What exit code integer grep returns when it doesn't match a string?

I know it returns 0 when it does match and I assume it returns 1 when it doesn't.

Is that correct?

  • You assume correctly. man pages confirm, as does grep --help 2>&1|grep Exit which yields "Exit status is 0 if any line is selected, 1 otherwise;" – steve Jun 16 '18 at 18:17
4

man grep helps:

EXIT STATUS
    The grep utility exits with one of the following values:

    0     One or more lines were selected.
    1     No lines were selected.
    >1    An error occurred.

Also, for GNU Grep:

However, if the -q or --quiet or --silent option is used and a line is
selected, the exit status is 0 even if an error occurred. Other grep 
implementations may exit with status greater than 2 on error.

And, depending on the implementation:

Normally, exit status is 0 if matches were found, and 1 if
no  matches  were found.  (The -v option inverts the sense
of the exit status.)

To test yourself, put the following in a script and run it.

#!/bin/bash
echo -n "Match: "
echo grep | grep grep >/dev/null; echo $?
echo -n "Inverted match (-v): "
echo grep | grep -v grep; echo $?
echo -n "Nonmatch: "
echo grep | grep grepx; echo $?
echo -n "Inverted nonmatch (-v): "
echo grep | grep -v grepx >/dev/null; echo $?
echo -n "Quiet match (-q): "
echo grep | grep -q grep; echo $?
echo -n "Quiet nonmatch (-q): "
echo grep | grep -q grepx; echo $?
echo -n "Inverted quiet match (-qv): "
echo grep | grep -qv grep; echo $?
echo -n "Inverted quiet nonmatch (-qv): "
echo grep | grep -qv grepx; echo $?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.