Let's say I have an array:
arr=(abcdef)
If I want to get the last element of an array, I usually have to get the total number of elements, subtract one and use this 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 indices:
$ echo ${arr[-1]} f $ echo ${arr[-2]} e
So, I wonder: when was this introduced? Is it possible to use other shells like ksh, zsh ...?
My research shows:
Bash -4.3-rc1 is available for FTP
but. Fixed a bug that caused the assignment of an undefined variable using a negative index to lead to a segmentation error.
b. Fixed a bug that caused the assignment of a string variable using a negative index to use the wrong index.
...
x Now the shell allows you to assign, reference and remove elements of indexed arrays using negative indices (a [-1] = 2, echo $ {a [-1]}) that are returned from the last element of the array.
And bash guide 4.3, on arrays
A reference to an array variable without an index is equivalent to referring to index 0. If the index used for the reference element of the indexed array is evaluated to a number less than zero, it is interpreted as a relative array exceeding the maximum value, therefore negative indices are returned from the end of the array, and index -1 refers to the last item .
But I wonder if this was already in Bash 4.2, as the first resource mentions a fixed bug.
arrays bash shell
fedorqui
source share