6

How do I ignore the division by zero error in Bash?

Example 1: (Doesn't work)

echo $((1/0)); echo "yay";
echo $((1/0)) || echo "yay";

Example 2:

echo -n $(echo -n $((1/0))) 2> /dev/null; echo "yay";

Is there an easier way than example 2, that would default to a specific value, when a division by zero is encountered.

Tyilo
  • 5,981

4 Answers4

4

Bash doesn't have a way to trap divisions by 0, nor do ash, ksh93, pdksh or zsh. The only ways to trap divisions by 0 are to detect them before they happen (check every denominator before performing the division) or to do them in a subshell.

If you do the arithmetic in a subshell, you can use the subshell's exit status to know whether an error (division by 0 or other) happened.

x=$(echo $(($a/$b)))
if [ $? -ne 0 ]; then
  echo "$b is 0 or some other arithmetic error occurred"
fi
2

well, other than if (($divisor == 0)); then SHUT_DOWN_EVERYTHING; I think you could use a subshell:

(echo $((1/0))) 2>/dev/null || echo yay

but notice this is silently ignoring the error as in your example code, it's not what you asked for that is a "default value" so why don't explain what are you trying to do instead?

Samus_
  • 219
0

we use a small function in our scripts

#!/bin/sh
divisor_valid "$myvar" || myvar=1
x=$(( 1000 / myvar ))
y=$(( 1000 % myvar ))

this way it's still readable and we avoid the cpu-intensive subshell.

the helper-functions are:

isnumber(){ test 2>/dev/null ${1:-a} -eq "${1##*[!0-9-]*}";}
divisor_valid(){ isnumber $1||return;case $1 in 0|-0)false;;esac;}

we are using busybox-ash, but it should work(tm) on POSIX

0

SIGFPE (signal number 8) is propably the signal you have to catch here.

Install a signal handler for that one:

trap "echo divide by zero >&2 ; exit 1 " SIGFPE

Update: It seems bash has its own handler for this which can`t be overridden. I transferred the solution from a plain C-program to bash-syntax...

Well - this method should work for other traps...

Nils
  • 18,492
  • No, the division by zero causes a fatal error without triggering any signal handler. – Gilles 'SO- stop being evil' Dec 30 '11 at 22:43
  • 1
    @Gilles You are wrong (and I am, too). man bash: "Evaluation is done in fixed-width integers with no check for overflow, though division by 0 is trapped and flagged as an error." But this trap seems to be bash-internal. – Nils Dec 31 '11 at 21:47