Divide by zero in ternary statement in bash on RHEL6 but not RHEL7

56 views Asked by At

UPDATE:

RHEL7 bash version: 4.2.46(2)-release (x86_64-redhat-linux-gnu)

RHEL6 bash version: 4.1.2(1)-release (x86_64-redhat-linux-gnu)

Okay, so here's a weird one....

I'm remotely executing a bash script on a large number of RHEL6 and RHEL7 servers. A few lines of the script use ternary notation (to save LOC). On the RHEL7 servers, it works fine. On some RHEL6 servers, it throws a divide by zero error every single time.

For context ternary expressions have the following syntax:

EXPR1 ? EXPR2 : EXPR3

If EXPR1 is true, EXPR2 evaluates, otherwise EXPR3 evaluates.

RHEL7 test (works correctly)

> cat /etc/redhat-release
Red Hat Enterprise Linux Server release 7.9 (Maipo)
> rpm -qa | grep bash
bash-4.2.46-35.el7_9.x86_64
> D21T=569
> NUM=2
> D21A=$((NUM<3 ? D21T/NUM : 9999))
> echo $D21A
284
> D21A=$((NUM<3 ? D21T/NUM : D21T/(NUM-2)))
> echo $D21A
284

RHEL6 test (divide by zero)

$ cat /etc/redhat-release
Red Hat Enterprise Linux Server release 6.10 (Santiago)
$ rpm -qa | grep bash
bash-4.1.2-48.el6.x86_64
$ D21T=569
$ NUM=2
$ D21A=$((NUM<3 ? D21T/NUM : 9999))
$ echo $D21A
284
$ D21A=$((NUM<3 ? D21T/NUM : D21T/(NUM-2)))
-bash: NUM<3 ? D21T/NUM : D21T/(NUM-2): division by 0 (error token is ")")

I'm completely at a loss why this would occur. I suspect a bug in that version of bash, but I can't find it, or I searching for the wrong thing. In any case, it appears as though EXPR3 is evaluating before EXPR1 is tested, but I can't be sure.

Part of me just wants to walk away and use and if statement, but I'd like to work out what is really going on here!

Regards,

Wayne

  • Tried changing variable values and increasing the number of parentheses.
0

There are 0 answers