1

If I use grep -q in combination with -v to return 0 if there are no matches or 1 if there is a match, it works as long as input is a single line:

$ echo 'abc' | grep -q -v a; echo $?
1
$ echo 'abc' | grep -q -v x; echo $?
0

But if the input is multi-line, grep will always return 0:

$ echo -e 'a\nb\nc' | grep -q -v a; echo $?
0
$ echo -e 'a\nb\nc' | grep -q -v x; echo $?
0

What is the reason for such behavior?

I know that the correct way in this case would be to use ! grep -q instead of grep -q -v, but I still want to know the answer.

Thunderbeef
  • 257
  • 1
  • 8

1 Answers1

2

Per grep manual:

-v, --invert-match
         Selected lines are those not matching any of the specified patterns.

If you supply only one line abc and tell grep to select only lines not matching a you get an empty output and return code equal to 1.

If you supply three lines a, b, and c and tell grep to select only those not matching a you get b and c in output and 0 as a return code.

$ echo -e 'a\nb\nc' | grep -v a; echo $?
b
c
0
techraf
  • 5,831
  • 10
  • 33
  • 51