gpt4 book ai didi

arrays - 获取 Bash 数组中的最后一个元素

转载 作者:行者123 更新时间:2023-11-29 08:55:26 29 4
gpt4 key购买 nike

假设我有一个数组:

arr=(a b c d e f)

如果我想获取数组的最后一个元素,我通常必须获取元素的总数,减去一个并使用该数字作为索引调用:

$ echo ${#arr[@]}
6
$ echo ${arr[${#arr[@]}-1]}
f

然而,I see最近(Bash 4.2 - 4.3)你可以使用负索引:

$ echo ${arr[-1]}
f
$ echo ${arr[-2]}
e

所以我想知道:这是什么时候引入的?它也可以被 ksh、zsh 等其他 shell 使用吗?

我的研究表明:

Bash-4.3-rc1 available for FTP

a. Fixed a bug that caused assignment to an unset variable using a negative subscript to result in a segmentation fault.

b. Fixed a bug that caused assignment to a string variable using a negative subscript to use the incorrect index.

...

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 manual 4.3, on Arrays

Referencing an array variable without a subscript is equivalent to referencing with a subscript of 0. If the subscript used to reference an element of an indexed array evaluates to a number less than zero, it is interpreted as relative to one greater than the maximum index of the array, so negative indices count back from the end of the array, and an index of -1 refers to the last element.

但我想知道这是否已经在 Bash 4.2 中,因为第一个资源提到了一个已修复的错误。

最佳答案

据我所见https://tiswww.case.edu/php/chet/bash/CHANGES ,新特性在这部分:

This document details the changes between this version, bash-4.3-alpha, and the previous version, bash-4.2-release.

...

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.

修复在:

This document details the changes between this version, bash-4.3-beta2, and theprevious version, bash-4.3-beta.

1 Changes to Bash

a. Fixed a bug that caused assignment to an unset variable using a negative subscript to result in a segmentation fault.

b. Fixed a bug that caused assignment to a string variable using a negative subscript to use the incorrect index.

它修复了 Bash 4.3 中的一项新功能。

关于arrays - 获取 Bash 数组中的最后一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36977855/

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