Bash Array – Get Index of Last Element Without Loop

arraybash

In bash, is it possible to get the index of the last element of an array (that might be sparse) without looping through the entire array like so:

a=( e0 e1 ... )
i=0
while [ "$i" -lt $(( ${#a[@]} - 1 )) ]
do
  let 'i=i+1'
done
echo "$i"

Since at least bash v 4.2, I can get the value of the last element in an array using

e="${array[-1]}"

but that will not get me the positive index since other elements may have the same value.

Best Answer

In case of an array which is not sparse, last index is number of elements - 1:

i=$(( ${#a[@]} - 1 ))

To include the case of a sparse array, you can create the array of indexes and get the last one:

a=( [0]=a [1]=b [9]=c )

indexes=( "${!a[@]}" )
i="${indexes[-1]}"

echo "$i"
9
Related Question