3

In Bash how can one get the last index of an array?

This works: $((${#array[@]} - 1)) but is not very pretty.
To get the last element of an array one can do ${myarray[-1]} is there a similar option for index?

5
  • declare -i index; index=${#array[@]}-1; echo $index? Commented Aug 22, 2021 at 14:08
  • 2
    @Cyrus not the way to get last index with sparse array. Commented Aug 22, 2021 at 14:10
  • take a look at this Q&A re: is array sparse/dense; part of the req is to find the last index; Socowi's answer refers to a custom builtin that could be modified to return the last index; my answer, along with a slew of comments, looks at a few ideas for finding the last index (ie, basically parsing the output from typeset -p); keep in mind we were looking at performance related issues for large arrays; for (relatively) small arrays any of the ideas presented at that link would likely be sufficient for this OP's req Commented Aug 22, 2021 at 14:18
  • should probably update the question to verify if this is (not) an associative array; assuming a (relatively) small (associative) array, one brute force idea: printf "%s\n" "${!array[@]}" | sort -n | tail -1 Commented Aug 22, 2021 at 14:27
  • Is there a way of reading the last element of an array with bash? explains negative indices. Commented May 9, 2024 at 12:35

2 Answers 2

8

If you're working with sparse arrays that have had elements unset:

indexes=( "${!array[@]}" )
lastindex=${indexes[-1]}

otherwise your $((${#array[@]} - 1)) is the way. Shell isn't pretty.

Sign up to request clarification or add additional context in comments.

1 Comment

If using zsh instead of bash, it's lastindex=${(k)array[-1]}
1

Get the last index of an array, regardless if it is sparse or not:

#!/usr/bin/env bash

array=([4]=foo [1]=bar [5]=cux [0]=baz)

# Capture all the indexes of the array
arrindexes=("${!array[@]}")

# Print the last index and element
last_index=${arrindexes[-1]}
printf 'Last index is: %d\n' "$last_index"
printf 'Last element at index %d is: %s\n' "$last_index" "${array[last_index]}"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.