Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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
add comment

3 Answers

up vote 2 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"
fi
share|improve this answer
add comment

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
add comment

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
add comment

Your Answer

 
discard

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.