Linux grep return code

I am trying to understand why the following returns code 1.

echo 'Total' | grep -c No 0 

So the "No" in "Total" does not exist. But then, looking at his return code, I see it as 1.

 echo $? 1 

Why is the return code displayed as 1? Is there any way around this?

+21
linux bash shell grep
source share
2 answers

According to the man grep page, the -c flag is for

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

So you see the hit counter and are not confused with the grep exit code. Code 1 caused by the absence of lines matching the input.

Look at another case

 echo 'No' | grep -c No 1 echo $? 0 

Also read on EXIT CODES on the man grep page,

OUTPUT STATE Normally, the output status is 0 if a line is selected, 1 if no lines are selected, and 2 if an error occurs.

+25
source share

The exit code is 1 because grep didn't match anything.

EXIT STATUS The exit status is 0 if the selected rows are found, and 1 if not found. If an error occurs, the exit status is 2. (Note. The POSIX error handling code must check a value of "2" or more.)

The output is zero because the Total counter is zero. This is due to the -c option:

-c, - -c ount Suppress normal output; instead, output the number of matching lines for each input file. Using the -v, --invert-match option (see below), count mismatched lines. (-c is defined by POSIX.)

If you want to force exit code 0, you can simply add || true || true || true || true your command:

 echo 'Total' | grep -c No || true 
+15
source share

All Articles