问题描述
说我有一个数组:
arr=(a b c d e f)
如果要获取数组的最后一个元素,通常必须获取元素的总数,减去一个,然后使用该数字作为索引:
If I want to get the last element of the array, I normally have to get the total number of elements, substract one and use that number to call as an index:
$ echo ${#arr[@]}
6
$ echo ${arr[${#arr[@]}-1]}
f
但是,我看到了最近(Bash 4.2-4.3)可以使用负索引:
However, I see that recently (Bash 4.2 - 4.3) you can use negative indexes:
$ echo ${arr[-1]}
f
$ echo ${arr[-2]}
e
所以我想知道:什么时候引入的?
So I am wondering: when was this introduced? Is it also usable by other shells like ksh, zsh...?
我的研究表明:
b.修复了导致使用以下命令分配给字符串变量的错误: 负下标以使用错误的索引.
b. Fixed a bug that caused assignment to a string variable using a negative subscript to use the incorrect index.
...
x. Shell现在允许分配,引用和取消设置元素 带有负下标(a [-1] = 2,echo $ {a [-1]}的索引数组) 从数组的最后一个元素开始倒数.
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中,因为第一个资源提到了已修复的错误.
But I wonder if this was already in Bash 4.2, since the first resource mentions a bug that was fixed.
推荐答案
据我在 https://tiswww.case.edu/php/chet/bash/CHANGES ,新功能就在此部分:
As far as I can see in https://tiswww.case.edu/php/chet/bash/CHANGES, the new feature is in this part :
...
x.现在,shell允许使用负下标(a [-1] = 2,echo $ {a [-1]})分配,引用和取消设置索引数组的元素,这些元素从数组的最后一个元素开始计数.
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.
修复:
1对Bash的更改
a.修复了导致 使用负下标分配给未设置的变量会导致分段错误.
a. Fixed a bug that caused assignment to an unset variable using a negative subscript to result in a segmentation fault.
b.修复了导致使用负下标分配给字符串变量以使用错误索引的错误.
b. Fixed a bug that caused assignment to a string variable using a negative subscript to use the incorrect index.
它修复了Bash 4.3中的一项新功能.
It a fix of a new feature in Bash 4.3.
这篇关于获取Bash数组中的最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!