是否有内置的 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)