Prevent grep from exiting in case of nomatch

echo "anything" | { grep e || true; }

Explanation:

$ echo "anything" | grep e
### error
$ echo $?
1
$ echo "anything" | { grep e || true; }
### no error
$ echo $?
0
### DopeGhoti's "no-op" version
### (Potentially avoids spawning a process, if `true` is not a builtin):
$ echo "anything" | { grep e || :; }
### no error
$ echo $?
0

The "||" means "or". If the first part of the command "fails" (meaning "grep e" returns a non-zero exit code) then the part after the "||" is executed, succeeds and returns zero as the exit code (true always returns zero).


A robust way to safely and optionally grep messages:

echo something | grep e || [[ $? == 1 ]] ## print 'something', $? is 0
echo something | grep x || [[ $? == 1 ]] ## no output, $? is 0
echo something | grep --wrong-arg e || [[ $? == 1 ]] ## stderr output, $? is 1

According to posix manual, exit code:

  • 1 means no lines selected.
  • > 1 means an error.

Another option is to add another command to the pipeline - one that does not fail:

echo "anything" | grep e | cat

Because cat is now the last command in the pipeline, it's the exit status of cat, not of grep, that will be used to determine if the pipeline failed or not.