Bash:数组索引的算术扩展-是否需要美元符号? [英] Bash: arithmetic expansion in array indices - is the dollar sign needed?

查看:79
本文介绍了Bash:数组索引的算术扩展-是否需要美元符号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在bash中的数组索引中使用算术扩展时,如下所示:

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"

或更确切地说:

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

?
在我的bash本地副本中,这两种变体似乎都可以工作-版本为4.3.30.
我希望只有后者能起作用,因为我认为只有一个能返回算术表达式的结果.但是: Bash-数组索引中的算术我读到只有第一个可能使用较旧版本的bash(?).那么,哪一个实际上是正确的呢?为什么第一个起作用?我还没有找到具体的答案.

?
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.

推荐答案

在数组中,bash将[]之间的表达式视为算术运算.因此

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

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

是完美的.编写f[((i++))]也是正确的,但是在这种情况下,(())不会被视为算术扩展运算符,而是被视为嵌套括号.

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

请注意,((expr))会对expr求值,如果为true,则成功,而$((expr))作为其值扩展.所以f[$((i++))]也是正确的.

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

最后,f[$i++]不是您想要的,因为先扩展了$i.例如,i=j ; f[$i++]将扩展为f[j++].

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++].

备注:一个奇怪的功能是bash在没有$符号的情况下在算术模式下可以扩展所有内容:

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")'

这篇关于Bash:数组索引的算术扩展-是否需要美元符号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆