arrays - Bash 脚本数组

标签 arrays bash

我是 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/

相关文章:

c - 我修改的代码中出现未处理的异常

关联数组中的 PHP 三元语句设置键和值?

c++ - 多维数组c++

mysql - 无法从终端执行 mysql 命令

linux - 无法在 bash 脚本中创建第三个参数(在 $* 之后)

linux - tail -f OR less +F 如何高亮新行

javascript - 将 SQL 查询结果从 PHP 传递到 Javascript 数组

访问 numpy 数组的移位版本的 Pythonic 方法?

arrays - 在 Bash 中如何将目录列表存储到数组中(然后将它们打印出来)?

bash - 删除超过 30% 小写字母的行