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

前端之家收集整理的这篇文章主要介绍了数组 – 获取Bash数组中的最后一个元素前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
说我有一个数组:
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

所以我想知道:这是什么时候介绍的?是否也可以被其他shell使用,比如ksh,zsh ……?

我的研究表明:

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中,因为第一个资源提到了一个修复过的bug.

据我所知,在 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,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中新功能的修复.

猜你在找的Bash相关文章