Why does bc exit 0 when dividing by 0

bccommand lineposix

I was trying to think of a quick and illustrative way to generate a non-successful exit status and thought dividing by zero with the bc would be a good idea.

I was suprised to discover that although it does generate a runtime error, the exit status is still 0:

$ echo 41 + 1 | bc
42
$ echo $?
0
$ echo 42/0 | bc
Runtime error (func=(main), adr=6): Divide by zero
$ echo $?
0
  • Why does the bc utility not fail with a non-zero exit status?

Note: For a quick non-zero exit status I'm using return 1

Also, from shell-tips:

$ expr 1 / 0
expr: division by zero
$ echo $?
2

Best Answer

bc implementations differ a bit in their return status, but the general idea is that if you supply valid input then bc exits with the status 0. 42/0 is valid input: there's no read error, and it's even a syntactically valid expression, so bc returns 0. If you passed a second line with another operation, bc would perform it. This is different from expr whose purpose is to evaluate a single arithmetic expression; here the outcome of that single expression determines the return status.

The most straightforward way to generate an exit status that indicates failure is to call false. Things like expr 1 / 0 only have their place in obfuscated programming contests.