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?
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.
zsh instead of bash, it's lastindex=${(k)array[-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]}"
declare -i index; index=${#array[@]}-1; echo $index?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 reqprintf "%s\n" "${!array[@]}" | sort -n | tail -1