help-bash
[Top][All Lists]

## Re: Order of command substitution and arithmetic expansion

 From: Greg Wooledge Subject: Re: Order of command substitution and arithmetic expansion Date: Sat, 13 Nov 2021 14:36:40 -0500

```On Sat, Nov 13, 2021 at 02:21:55PM -0500, Dongbo Hu wrote:
> > If arithmetic expansion happened last in all cases, then the first result
> > should have been the same as the second result.
>
> Thank you for your reply. I suppose you meant "If arithmetic expansion
> happened last in all cases, then the first result should have been DIFFERENT
> from the second result?

It's unfortunate that you deleted the examples you were commenting on.
Here's what I posted:

unicorn:~\$ i=7
unicorn:~\$ : \$((i++)) \$(declare -p i >&2)
declare -- i="8"

unicorn:~\$ i=7
unicorn:~\$ : \$(declare -p i >&2) \$((i++))
declare -- i="7"

By "first result" I mean i=8, and by "second result" I mean i=7.  Clearly
these are different results.

In this case we're looking at the first result, i=8.  We get this result
because the arithmetic expansion happens first, incrementing the value
of i.  Then the command substitution happens second, and shows us the
new value of i (8).

In a hypothetical world where arithmetic expansions always happen after
command substitutions, the command substitution would have gone first,
and would have showed us the original value of i (7).  Then the arithmetic
expansion would have gone second, and incremented i -- but we wouldn't
see this, because I didn't put anything in the example that shows it.

So, we know that there isn't anything in bash that forces the arithmetic
expansion to happen later.  Looking *strictly* at the first result, we
can conclude that either (a) arithmetic expansions always happen first,
or (b) it goes left to right.

Thus, we have the second result, which is the reverse of the first result.
>From this one, we can conclude that either (a) arithmetic expansions
always happen last, or (b) it goes left to right.  Case (a) can't be
true, because that contradicts the first result.

So we're left with (b) it goes left to right.

```