Bash 3.2's behavior of logical or || operator in arithmetic expressions

Viewed 104

I experimented on the latest mac OS with a shell scrip "a.sh" with the following content (exact copy).

#!/bin/bash
echo $BASH_VERSION
a=0
(( a < 100 || 1 / a < 2 )) && echo ok

I got:

3.2.57(1)-release
./a.sh: line 4: ((: a < 100 || 1 / a < 2 : division by 0 (error token is "< 2 ")

Since a < 100 is already true, I thought 1 / a < 2 wouldn't be evaluated.

Can someone help me understand this?

1 Answers

There are two circumstances you got this error:

  1. Bash 3.2.57 evaluates both sides of a logical or within an arithmetic expression.

  2. or because you used a single | bit-wise ∨, rather than a double || logical ∨ boolean expression operator:

LC_ALL=C bash -c 'a=0; (( a < 100 | 1 / a < 2 )) && echo ok'

bash: ((: a < 100 | 1 / a < 2 : division by 0 (error token is "a < 2 ")

LC_ALL=C bash -c 'a=0; (( a < 100 || 1 / a < 2 )) && echo ok'

ok

Reason: | is the bit-wise or operator.

When used as:

a < 100 | 1 / a < 2,

the bit-wise or applies as:

100 | 1,

witch in binary is equivalent to 01100100 ∨ 0000000101100101 binary or 101 base-10.

Finally:

a < 100 | 1 / a < 2 turns-out to be:

a < 101 / a < 2.

When a=0:

0 < 101 / 0 < 2

Related