0

How to check grep is empty when set -e is enabled?

set -e

# ... lots of other lines that need set -e

echo foo | grep bar
EXIT_CODE=$?

if [  "${EXIT_CODE}" -eq 0 ]; then
  echo "is there"
else
  echo "isn't there"
fi

# ... lots of other lines that need set -e

The script will stop when EXIT_CODE != 0, instead of printing "isn't there", which is the wanted behavior in this snippet.

Obviously, I can just unset e (set +e) before and after the grep check.

set -e

# ... lots of other lines that need set -e

set +e
echo foo | grep bar
EXIT_CODE=$?
set -e

if [  "${EXIT_CODE}" -eq 0 ]; then
  echo "is there"
else
  echo "isn't there"
fi

# ... lots of other lines that need set -e

Is there another better more elegant solution?

YFl
  • 845
  • 7
  • 22
  • 1
    Note that if you just do the standard check with `if echo foo | grep bar; then ....` instead of explicitly assigning `$?` to a variable, then the default behavior of `set -e` (whatever that is!!, see decades of discussion about the ambiguity of the expression "default behavior of set -e") should do what you want. – William Pursell Aug 02 '22 at 18:34
  • @WilliamPursell, thanks. `if echo foo | grep bar`, which in this case is empty, will enter the if or the else? – YFl Aug 02 '22 at 19:34
  • 1
    If `grep` matches the pattern, it will return 0 and the `if` clause is entered. If `grep` does not match the pattern, it will return non-zero and the else clause is entered. – William Pursell Aug 02 '22 at 19:54
  • 1
    Do read https://mywiki.wooledge.org/BashFAQ/105 – William Pursell Aug 02 '22 at 20:45
  • Interesting one. Which opposes to this: http://redsymbol.net/articles/unofficial-bash-strict-mode/ – YFl Aug 04 '22 at 10:14

0 Answers0