Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
up vote 4 down vote accepted

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"
share|improve this answer

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?

share|improve this answer

we use a small function in our scripts

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

share|improve this answer

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

share|improve this answer
No, the division by zero causes a fatal error without triggering any signal handler. – Gilles Dec 30 '11 at 22:43
@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

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.