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 ... )
while [ "$i" -lt $(( ${#a[@]} - 1 )) ]
  let 'i=i+1'
echo "$i"

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


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

  • 1
    The loop in question seems pointless. You might as well have written i=$((${#a[@]}-1)).
    – muru
    Commented May 1, 2022 at 9:18
  • 2
    @muru Since arrays might be sparse $(( ${#a[@]} - 1 )) will give the number of elements in the array. That may or may not be the same as the index of the last element.
    – fuumind
    Commented May 1, 2022 at 10:41
  • That may be, but the loop you show in the question is pointless.
    – muru
    Commented May 1, 2022 at 13:13

2 Answers 2


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[@]}" )

echo "$i"
lst=( [0]=1 [1]=2 [9]=3 )
echo ${lst[@]@A}           # show elements and indexes
echo ${lst[-1]}            # last  element
echo ${!lst[@]}            # list of indexes
: ${!lst[@]} ; echo $_     # last index

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .