Is there a way of reading the last element of an array with bash?

As of bash 4.2, you can just use a negative index ${myarray[-1]} to get the last element. You can do the same thing for the second-last, and so on; in Bash:

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.

The same also works for assignment. When it says "expression" it really means an expression; you can write in any arithmetic expression there to compute the index, including one that computes using the length of the array ${#myarray[@]} explicitly like ${myarray[${#myarray[@]} - 1]} for earlier versions.


Modern bash (v4.1 or better)

You can read the last element at index -1:

$ a=(a b c d e f)
$ echo ${a[-1]}
f

Support for accessing numerically-indexed arrays from the end using negative indexes started with bash version 4.1-alpha.

Older bash (v4.0 or earlier)

You must get the array length from ${#a[@]} and then subtract one to get the last element:

$ echo ${a[${#a[@]}-1]}
f

Since bash treats array subscripts as an arithmetic expression, there is no need for additional notation, such as $((...)), to force arithmetic evaluation.


bash array assignment, reference, unsetting with negative index were only added in bash 4.3. With older version of bash, you can use expression in index array[${#array[@]-1}]

Another way, also work with older version of bash (bash 3.0 or better):

$ a=([a] [b] [c] [d] [e])
$ printf %s\\n "${a[@]:(-1)}"
[e]

or:

$ printf %s\\n "${a[@]: -1}"
[e]

Using negative offset, you need to separate : with - to avoid being confused with the :- expansion.

Tags:

Bash

Array