相关疑难解决方法(0)

计算bash数组中元素的个数,其中数组的名字是动态的(即存储在一个变量中)

问题的简要说明:

是否有内置的 bash 方法来计算 bash 数组中元素的数量,其中数组的名称是动态的(即存储在变量中),而无需完全复制数组或使用eval?

更多信息:

使用 bash 参数替换,可以执行以下操作:

  • 确定数组的长度:
    myArr=(A B C); echo ${#myArr[@]}.
  • 按名称间接引用变量:(
    NAME=myVar; echo ${!NAME}
    这也适用于数组元素):
    NAME=myArr[1]; echo ${!NAME}

但是如果一个数组的名称存储在另一个变量中,如何确定数组中元素的数量?(人们可能认为这是一种组合上述两个参数替换。)例如:

myArr=(A B C D)
NAME=myArr
# Get the number of elements in the array indirectly referenced by NAME.
count=${#$NAME[@]}  # This syntax is invalid. What is the right way?
Run Code Online (Sandbox Code Playgroud)

以下是所有失败的多次尝试:

  # Setup for following attempts:
  myArr=(A B C D)
  NAME=myArr
  EXPR1=$NAME[@]          # i.e. EXPR1='myArr[@]'
  EXPR2=#$NAME[@]         # i.e. EXPR2='#myArr[@]' …
Run Code Online (Sandbox Code Playgroud)

bash array parameter shell-script shell-builtin

11
推荐指数
1
解决办法
2万
查看次数

标签 统计

array ×1

bash ×1

parameter ×1

shell-builtin ×1

shell-script ×1