8

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.

3
  • 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

14

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
1
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
0

You must log in to answer this question.

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