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

11,712

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.
Share:
11,712
tonix
Author by

tonix

Updated on June 12, 2022

Comments

  • tonix
    tonix over 1 year

    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?

  • tonix
    tonix almost 9 years
    Thank you for your response! It works. Just a clarification. When you say which will always print exit status of previous command and that will always be 0 whether pattern is found or not. but if the pattern is not found, greps exits with one, so shouldn't it be one?
  • anubhava
    anubhava almost 9 years
    grep -E '^nothing' List.txt | echo $? prints exit status of the command that was executed before grep not this grep command.
  • tonix
    tonix almost 9 years
    All right, thanks that was what I needed to understand!
  • volvox
    volvox over 3 years
    grep -s is recommended instead of -q for Posix compat.