我是 bash 脚本新手,并试图了解事情是如何工作的。一切都有点奇怪..
以下内容可以放入脚本中或输入到 shell 中:
declare -a A=("foo" "bar")
B=1
[ ${A[B]} == ${A[$B]} ] && echo "wTF" || echo ";)"
这让我在我的 debian squeeze 和 cygwin 1.7.11-1 上“wTF”
所以。为什么${A[B]}
有效?
最佳答案
来自the Bash Reference Manual, §6.7 "Arrays" :
Indexed arrays are referenced using integers (including arithmetic expressions […]) and are zero-based; […] ¶ The subscript is treated as an arithmetic expression that must evaluate to a number greater than or equal to zero.
因此,实际上,${A[B]}
表示 ${A[$((B))]}
。当您想要类似 ${A[B-1]}
之类的内容时,这很方便。
算术表达式的解释见 §6.5 "Shell Arithmetic" ,其中部分内容为:
Within an expression, shell variables may also be referenced by name without using the parameter expansion syntax.
因此,$((B))
表示 $(($B))
(除了前者在某些方面更聪明,例如使用零而不是空白作为未初始化变量的默认值)。
关于arrays - Bash 脚本数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9763743/