Search code examples
arraysbashlanguage-lawyerconditional-operatorside-effects

Is bash supposed to evaluate array index expressions for side-effects even when the indexing expression goes unused?


Weird thing I recently discovered: At least on my version of bash (4.2), it seems like the conditional operator does not evaluate the untaken path normally, but it does so for array indexing expressions. Example:

$ echo $i  # i initially unset

$ ((0?++i:0)); echo $i  # As expected, i is not touched when false branch taken, like any sane language

$ ((0?a[++i]:0)); echo $i  # But when untaken branch indexes, and indexing expression has side-effect... WTF?!?
1
$ ((0?a[++i]:0)); echo $i  # Continues building on each call...
2

This was quite surprising, to say the least. It feels csh-like in its inconsistency. Is this a bug in my particular version of bash, or is it required in some way due to the interaction of rules for arithmetic evaluation and/or array indexing (where array indexing itself already imposes arithmetic evaluation rules) in some spec more detailed than man bash? (or did I miss where this is required in the Bash man pages?)


Solution

  • That was a bug, which was fixed in Bash-4.4 patch 8.

    Related links:

    Though, I don't have an explanation why ((0?++i:0)) isn't affected by this bug.