I have a question about bash's parameter expansion, inside a comma expression, inside an arithmetic expression. I have two statements that I thought should be equivalent, but they're not.
Why does the bash line
n=3; k=10; echo $((n++,k=$n))
3 instead of
4? (It sets
4, as I expected, but sets
In contrast, the bash line
n=3; k=10; echo $((n++,k=n))
4, as I expected. (It sets
I've tried replacing
n=n+1, and with
n=$((n+1)) in both bash lines, and they all yield the same discrepancy:
3 in all the scripts, and
4 in all of them.
My understanding is that, if the value of
n is an integer (which it is),
n should have the same value inside an arithmetic expression. (And this is an arithmetic expression because of the
(( ... )) construct.) According to the bash manual, in the section Arithmetic Evaluation, in an arithmetic expression:
Shell variables are allowed as operands; parameter expansion is performed before the expression is evaluated. Within an expression, shell variables may also be referenced by name without using the parameter expansion syntax.
So why is bash treating
$n differently from
n in this example, and exactly how is it evaluating
I haven't been able to duplicate the issue without using the comma operator. The comma operator, from what I've always seen, computes each of its component subexpressions from left to right, including all the side effects of each component when that component is computed. The value of the comma expression is then the value of the last component computed (the rightmost one).
This question arose in the context of a much more complicated script, and I finally narrowed it down to this simple example which demonstrates the issue.
So, what am I misunderstanding about arithmetic expansion, parameter expansion, or the comma operator?
Note that I'm not looking for a workaround, since I have one already: the version with
n instead of
$n works as I expected. I just want to understand what bash is doing in the version with
$n, and why it does something different from the version with just