Bash – Preventing Grep from Causing Premature Termination in bash -e Script

basherror handlingexitgrep

This script does not echo "after":

#!/bin/bash -e

echo "before"

echo "anything" | grep e # it would if I searched for 'y' instead

echo "after"
exit

It also would if I removed the -e option on the shebang line, but I wish to keep it so my script stops if there is an error. I do not consider grep finding no match as an error. How may I prevent it from exiting so abruptely?

Best Answer

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).

Related Question