Get last element in Bash array
Say I have an array:
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
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...?
My research shows:
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.
And 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 .
But I wonder if this was already in Bash 4.2, since the first resource mentions a bug that was fixed.
As far as I can see in https://tiswww.case.edu/php/chet/bash/CHANGES, the new feature is in this part :
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.
The fix in :
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.
It a fix of a new feature in Bash 4.3.
链接地址: http://www.djcxy.com/p/91572.html上一篇: 有什么办法可以用socks proxy来使用aiohttp客户端吗?
下一篇: 获取Bash数组中的最后一个元素