12

The grep manual at the exit status section report:

EXIT STATUS
       The  exit  status is 0 if selected lines are found, and 1 if not
       found.  If an error occurred the exit status is 2.  (Note: POSIX
       error handling code should check for '2' or greater.)

But the command:

echo ".
..
test.zip"|grep -vE '^[.]'
echo $?

echo "test.zip
test.txt"|grep -vE '^[.]'
echo $?

The value returned is always 0. I would have expected 1 and 0. What am I doing wrong?

6
  • 4
    exit status is 1 if grep doesn't find any match.. both your given samples returns at least one matching line.. so exit status is 0 for both cases..
    – Sundeep
    Apr 9, 2018 at 9:55
  • You question could be replaced with: "Why does grep -vE '^[.]' <<<$'.\na'; echo $? output 0?" Apr 9, 2018 at 10:01
  • @Sundeep no '^[.]' match only what starts with a point, perhaps it is not clear that the input is multiline? Apr 9, 2018 at 12:14
  • @MichaWiedenmann yes but the problem is not that. Apr 9, 2018 at 12:15
  • 1
    @bandabassotti May I kindly suggest, that you are a little confused, sundeep explained that exactly because the line is multiline and there is a line which matches your pattern, you get your result. (Grep is line base.) Apr 9, 2018 at 12:40

1 Answer 1

4

Remember that grep is line based. If any line matches, you got a match. (In your first case test.zip matches (more precisely: you used -v therefore you have asked for lines that do not match your pattern, and test.zip does exactly that, i.e. does not match your pattern. As a result your grep call was successful). Compare

$ grep -vE '^[.]' <<<$'.\na'; echo $?
a
0

with

$ grep -vE '^[.]' <<<$'.\n.'; echo $?
1

Note how the first command outputs the line a, that is it has found a match, which is why the exit status is 0. Compare that with the second example, where no line was matched.

References

<<< is a here string:

Here Strings
    A variant of here documents, the format is:

           [n]<<<word

    The word undergoes brace  expansion,  tilde  expansion,  parameter  and
    variable  expansion,  command  substitution,  arithmetic expansion, and
    quote removal.  Pathname expansion and  word  splitting  are  not  per-
    formed.   The  result  is  supplied  as a single string, with a newline
    appended, to the command on its standard input (or file descriptor n if
    n is specified).
   $ cat <<<'hello world'
   hello world

$'1\na' is used to get a multi line input (\n is replaced by newline within $'string', for more see man bash).

$ echo $'1\na'
1
a

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.