11

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
banda bassotti
  • 113
  • 1
  • 1
  • 4
  • 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 09 '18 at 09:55
  • You question could be replaced with: "Why does `grep -vE '^[.]' <<<$'.\na'; echo $?` output 0?" – Micha Wiedenmann Apr 09 '18 at 10:01
  • @Sundeep no '^[.]' match only what starts with a point, perhaps it is not clear that the input is multiline? – banda bassotti Apr 09 '18 at 12:14
  • @MichaWiedenmann yes but the problem is not that. – banda bassotti Apr 09 '18 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.) – Micha Wiedenmann Apr 09 '18 at 12:40
  • `-v` selects the lines that are not matching the pattern. Both command lines you posted contain lines that are not matching the `^[.]` pattern. – axiac Apr 09 '18 at 12:51

1 Answers1

3

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 with -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
Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137