KunalC
KunalC

Reputation: 544

Bash exiting while performing numeric calculation

I am trying to execute the following logic in my bash script

#!/bin/bash
set -x
# Copy merchant files
set -o pipefail -o errexit

a=0
b=0
c=$(expr $a + $b)
if [[ $(expr $c) -lt 10 ]]; then
  echo true
fi

This never prints true as expected. The output produced is:

++ set -o pipefail -o errexit
++ a=0
++ b=0
+++ expr 0 + 0
++ c=0

Also the above logic does not work when a and b both are 0, if any one is non zero it works fine. And if I modify my logic and instead of calculating c use the expr directly in the if it works fine and prints true as expected irrespective of value of a and b

#!/bin/bash
set -x
# Copy merchant files
set -o pipefail -o errexit

a=0
b=0
if [[ $(expr $a + $b) -lt 10 ]]; then
  echo true
fi

Can someone please explain me what's wrong with the first piece of code.

Upvotes: 1

Views: 149

Answers (1)

tripleee
tripleee

Reputation: 189638

What's wrong is that expr will return a non-zero exit status (which the shell interprets as an error) if an arithmetic expression evaluates to zero. This is not immediately compatible with set -o errexit.

Since you are using Bash, the easy workaround is to not use expr at all.

c=$((a + b))
if [[ "$c" -lt 10 ]]; then
    echo true
fi

If you wish to stay with expr for some reason, the customary idiom is to trap errors you want to permit with || true or some variant.

c=$(expr "$a" + "$b") || true

When you refactored the calculation into the if clause, that's "some variant", i.e. errexit cannot trigger on a failure in the condition part of an if or while clause (obviously; otherwise, it would be impossible to write code with conditionals under set -o errexit).

Upvotes: 5

Related Questions