gpt4 book ai didi

arrays - Bash 数组中的负下标

转载 作者:太空狗 更新时间:2023-10-29 11:12:37 25 4
gpt4 key购买 nike

在创建一个简单的 bash 堆栈脚本后,我遇到了与 bash 数组相关的错误。

来自 Bash 手册:

An indexed array is created automatically if any variable is assigned to using the syntax:

name[subscript]=value

name[subscript]=value The subscript is treated as an arithmetic expression that must evaluate to a number. If subscript evaluates to a number less than zero, it is used as an offset from one greater than the array’s maximum index (so a subcript of -1 refers to the last element of the array).

不幸的是,我的本地机器上一切都运行良好,我的服务器环境略有不同。

负数下标适用于 Ubuntu 14.04/GNU bash 版本 4.3.11(1)。但是,当我尝试使用 GNU bash 版本 4.2.46(1) 在我的服务器上运行相同的脚本时,我遇到了以下错误:

line 46: [-1]: bad array subscript 

我尝试创建一个数组并直接从终端(不在脚本中)调用最后一个元素,它成功了:

user@local:~$ arr=( 1 2 3 4 5 )
user@local:~$ echo ${arr[-1]}
5

我在这里有点困惑。对此有任何解决方案或解决方法吗?

最佳答案

猜猜 Bash changelog 里有什么:

对于:此版本、bash-4.3-beta 和以前的版本,bash-4.3-alpha

x. The shell now allows assigning, referencing, and unsetting elements of indexed arrays using negative subscripts (a[-1]=2, echo ${a[-1]}) which count back from the last element of the array.

对于:此版本、bash-4.2-alpha、和之前的版本 bash-4.1-release

p. Negative subscripts to indexed arrays, previously errors, now are treated as offsets from the maximum assigned index + 1.

因此您的测试仅读取负偏移量(在 ~4.2 及更高版本中正常),但您的错误源于尝试分配或取消设置负偏移量(在 ~4.3 及更高版本中正常)。

也许您可以引用数组的长度并对其进行一些数学运算:
(阅读)${arr[${#arr[@]}-1]}
(分配)arr[${#arr[@]}-1]=last
(清除)unset arr[${#arr[@]}-1]

关于arrays - Bash 数组中的负下标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40131920/

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