【问题标题】:Bash - Get last index of arrayBash - 获取数组的最后一个索引
【发布时间】:2021-08-23 01:41:25
【问题描述】:

在 Bash 中如何获取数组的最后一个索引?

这可行:$((${#array[@]} - 1)) 但不是很漂亮。
要获取数组的最后一个元素,可以执行${myarray[-1]} 是否有类似的索引选项?

【问题讨论】:

  • declare -i index; index=${#array[@]}-1; echo $index?
  • @Cyrus 不是使用稀疏数组获取最后一个索引的方法。
  • 看看这个Q&A re: is array sparse/dense; req 的一部分是找到最后一个索引; Socowi 的答案是指可以修改为返回最后一个索引的自定义内置函数;我的回答,连同大量 cmets,着眼于寻找最后一个索引的一些想法(即,基本上解析来自 typeset -p 的输出);请记住,我们正在研究 large 数组的性能相关问题;对于(相对)小数组,该链接上提出的任何想法都可能足以满足此 OP 的要求
  • 应该可能更新问题以验证这是否(不是)关联数组;假设一个(相对)小(关联)数组,一个蛮力想法:printf "%s\n" "${!array[@]}" | sort -n | tail -1

标签: arrays bash


【解决方案1】:

如果您正在使用未设置元素的稀疏数组:

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

否则你的$((${#array[@]} - 1)) 就是方法。 Shell 不漂亮。

【讨论】:

  • 如果使用zsh而不是bash,则为lastindex=${(k)array[-1]}
【解决方案2】:

获取数组的最后一个索引,不管它是否稀疏:

#!/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]}"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-16
    • 2023-04-02
    • 1970-01-01
    • 2014-09-27
    • 1970-01-01
    • 2014-05-09
    • 2016-08-26
    • 1970-01-01
    相关资源
    最近更新 更多