加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-16 01:18:04 所属栏目:安全 来源:网络整理
导读:说我有一个数组: 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
说我有一个数组:
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中新功能的修复.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读