Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

bash - Arithmetic expansion in array indices - is the dollar sign needed?

When I use arithmetic expansion in an array index in bash, like this:

declare -a FILES
declare -i INDEX=0

for FILE in ./*
do
    FILES[((INDEX++))]="$FILE"
done

Do I need a dollar sign in front of ((...))?
So does it have to be:

FILES[((INDEX++))]="$FILE"

or rather:

FILES[$((INDEX++))]="$FILE"

?

In my local copy of bash both variants seem to work - it's version 4.3.30.

I would expect only the latter to work, because I think only that one returns the result of the arithmetic expression. But there: Bash - arithmetic in array index I've read that only the first might work with older versions of bash (?). So which one is actually correct? And why is the first one working? I haven't found a specific answer to that yet.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In arrays, bash considers expressions between []as arithmetic. Thus

i=2 ; f[i++]=10

is perfect. Writing f[((i++))] is also correct but in this case, (()) is not seen as the arithmetic expansion operator, but as nested parentheses.

Note that ((expr)) evaluates expr, then succeeds if it is true, while$((expr)) is expanded as its value. So f[$((i++))] is also correct.

Finally, f[$i++] is not what you want since $i is expanded first. For instance, i=j ; f[$i++] will be expanded as f[j++].

Remark: a strange feature is that bash expands all it can in arithmetic mode without the $ sign:

$ unset i j k f
$ i=j ; j=k ; k=5 ; f[i++]=10
$ declare -p i j k f
declare -- i="6"
declare -- j="k"
declare -- k="5"
declare -a f='([5]="10")'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...