Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The exit status code for the 'grep' command

Tags:

grep

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?

like image 856
banda bassotti Avatar asked Jan 18 '26 08:01

banda bassotti


1 Answers

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
like image 52
Micha Wiedenmann Avatar answered Jan 21 '26 09:01

Micha Wiedenmann