在bash中,如何在没有循环的情况下获取数组最后一个元素的索引

fuu*_*ind 8 bash array

在 bash 中,是否可以获取数组最后一个元素(可能是稀疏的)的索引,而无需像这样循环遍历整个数组:

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

至少从 bash v 4.2 开始,我可以使用以下命令获取数组中最后一个元素的

e="${array[-1]}"
Run Code Online (Sandbox Code Playgroud)

但这不会给我带来索引,因为其他元素可能具有相同的值。

tha*_*isp 14

如果数组不是稀疏的,最后一个索引是元素数 - 1:

i=$(( ${#a[@]} - 1 ))
Run Code Online (Sandbox Code Playgroud)

要包含稀疏数组的情况,您可以创建索引数组并获取最后一个:

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

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

echo "$i"
9
Run Code Online (Sandbox Code Playgroud)