The return code from 'grep' is not as expected on Linux


I’m struggling to see why the following is returning a code of 1.

echo 'Total' | grep -c No

So "No" doesn’t exists in "Total". But then looking up its return code I’m seeing it as 1.

echo $?

Why is return code showing up as 1? Is there a way to get around this?


According to man grep page, -c flag is for

-c, –count
Suppress normal output; instead print a count of matching lines for each input file.

So what you are seeing is the count of the match and not to be confused with the exit code of the grep match. The code 1 is because of no lines matching from the input.

Have a look at the other case,

echo 'No' | grep -c No

echo $?

Also to read on EXIT CODES on man grep page,

Normally the exit status is 0 if a line is selected, 1 if no lines were selected, and 2 if an error occurred.

Answered By – Inian

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published