微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

数组 – 获取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中新功能的修复.

原文地址:https://www.jb51.cc/bash/384252.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐