Get the last item in a Bash array

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.

+7
arrays bash shell
source share
1 answer

As far as I can see in https://tiswww.case.edu/php/chet/bash/CHANGES , a new function is in this part:

This document describes the changes between this version of bash -4.3-alpha, and the previous version, bash -4.2-release .

...

x Now the shell allows you to assign, reference and remove elements of indexed arrays using negative indexes (a [-1] = 2, echo $ {a [-1]}), which are returned from the last element of the array.

Correction:

This document describes the changes between this version of bash -4.3-beta2 and the previous version of bash -4.3-beta strong>.

1 Changes to Bash

but. Fixed a bug that caused the assignment of an unset variable with 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.

This is a fix for a new feature in Bash 4.3.

+4
source share

All Articles