gpt4 book ai didi

arrays - Bash 脚本数组

转载 作者:行者123 更新时间:2023-11-29 09:49:10 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com