[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

expansions upon arithmetic evaluation in array subscripts

From: Stephane Chazelas
Subject: expansions upon arithmetic evaluation in array subscripts
Date: Mon, 13 Oct 2014 15:28:26 +0100
User-agent: Mutt/1.5.21 (2010-09-15)

2014-10-13 09:02:38 -0400, Chet Ramey:
> You have to put it together.  A variable need not be expanded before
> arithmetic evaluation, so the evaluator expands, for instance, a bare
> `a' to `b[$(echo 1+1)]'.  When a variable is expanded, its value is
> treated as an expression to be evaluated.  An array subscript -- for an
> indexed array -- is an arithmetic expression.  All tokens in an arithmetic
> expression, including an array subscript, undergo variable expansion, word
> splitting, and quote removal.

Thanks. I'm still confused though.


a='1 + $b'
echo $((a))

a is expanded and the expansion is also evaluated as an
arithmetic expression, so why isn't $b expanded there?

Note that it's not only variable expansion, it's also tilde
(even though ~ is also an arithmetic operator) expansion.

$ HOME=1 a='b[~]'  bash -c 'b=(1 2 3); echo $((a))'

That means for instance that 

echo $((a[~foo]))

won't work on systems where there's a "foo" user.

It's also command substitution obviously.

Not process substitution though contrary to what I previously
said (which would have been a bigger problem for things like:

arr[x<(a+b) ? x : y]

I wasn't aware of word splitting. I didn't think that could
apply given that we're not in list context (splitting into
several words doesn't make sense where). That makes it a
difference with other shells.

$ a='1-+1' c='b[$a]' bash -c 'b=(1 2 3); IFS=-; echo $((c))'
$ a='1-+1' c='b[$a]' ksh -c 'b=(1 2 3); IFS=-; echo $((c))'

Again, I'd say it's not very consistent and doesn't make much sense:

$ a='1-+1' c='b[$a]' bash -c 'b=(1 2 3); IFS=-; echo $((c))'

$ a='1-+1' bash -c 'b=(1 2 3); IFS=-; echo $((b[$a]))'

Why splitting (and joinging with space?) in the first case and
not the second?


reply via email to

[Prev in Thread] Current Thread [Next in Thread]