Search code examples
shellterminalgrepexit-code

Terminal - Why the exit command of grep is 0 even if a match is not found?


I have this command:

grep -E '^nothing' List.txt | echo $?

Here grep doesn't match anything and I simply output its exit code. According to documentation of grep:

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 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.

But:

prompt:user$ grep -E '^nothing' List.txt | echo $?
0
prompt:user$

But why do I get 0 as output even if the match doesn't exist, should't I get the expected 1 exit code?


Solution

  • This is the problem:

    grep -E '^nothing' List.txt | echo $?
    

    By using single | you are sending output of grep to echo which will always print exit status of previous command and that will always be 0 whether pattern is found or not.

    You can use grep -q:

    grep -qE '^nothing' List.txt
    

    As per man grep:

     -q, --quiet, --silent
             Quiet mode: suppress normal output.  grep will only search a file until a match
             has been found, making searches potentially less expensive.