Conditional Grep Without Quiet Option in Bash

bashgrep

I always thought the quiet (-q) option had to be used when using grep conditionally. But re-reading the man page it seems like it should work without it.

So if you want to print matches and use it in a conditional, can you just do something like

grep PATTERN FILE && do_something_else

The only thing that makes me uncertain is that there appears to be a slight difference in exit status.

With -q,

  • grep will "exit immediately with zero status if any match is found, even if an error was detected".

Without -q

  • "The exit status is 0 if selected lines are found, and 1 if not found. If an error occurred the exit status is 2".

But I can't think of an example where the difference will become noticeable?

Best Answer

Here's an example:

$ echo "foo" > file
$ grep foo file wrongfile; echo "Exit status: $?"
file:foo
grep: wrongfile: No such file or directory
Exit status: 2
$ grep -q foo file wrongfile;  echo "Exit status: $?"
Exit status: 0

So, we have a file called file that contains the string foo. When I ran grep with -q on file and the nonexistent wrongfile, since file contained a match, grep exited with 0 status despite the "No such file" error.