6

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?

5

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.

  • +1 didn't think about the case with more than one file, is there any difference with 1? – user60101 Nov 16 '14 at 19:01
  • @BroSlow this was the first case that came to mind where you can find both an error and a hit. I can't think of any way to get both an error and a hit with one file. Perhaps if the file is truncated while it is being read but that's hard to test. – terdon Nov 16 '14 at 19:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy