Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash 作为数组名称一部分的变量_Bash - Fatal编程技术网

Bash 作为数组名称一部分的变量

Bash 作为数组名称一部分的变量,bash,Bash,我有一段代码: #!/bin/bash item01=('item1' '1' '20') item02=('item2' '4' '77') item03=('item3' '17' '15') zeroone=01 zerotwo=02 echo "" declare -a array=() array=${item$zeroone[@]} echo "" echo ${array[@]} echo "" 显然,这不起作用(糟糕的替代) 有没有办法让它发挥作用?这样一个变量就可以是数

我有一段代码:

#!/bin/bash

item01=('item1' '1' '20')
item02=('item2' '4' '77')
item03=('item3' '17' '15')
zeroone=01
zerotwo=02


echo ""
declare -a array=()
array=${item$zeroone[@]}
echo ""
echo ${array[@]}
echo ""
显然,这不起作用(糟糕的替代)

有没有办法让它发挥作用?这样一个变量就可以是数组名的一部分

而且,为了使这项工作特别有效:

array[0]=${item$zeroone[0]}


Thx更好地使用关联数组:

declare -A item=([1, 0]='item1' [1, 1]='1' [1, 2]='20')
...
item01=('item1' '1' '20')
item02=('item2' '4' '77')
item03=('item3' '17' '15')
zeroone=01
zerotwo=02

echo ""
ref="item${zeroone}[@]"
declare -a array=("${!ref}")  ## Still produces 3 arguments as if "${item01[@]}" was called
echo ""
echo "${array[@]}"
echo ""
访问元素:

one=1
echo "${item[$one, 0]}"
在循环中:

for ((I = 0; I <= 2; ++I)); do
    echo "${item[$one, $i]}"
done
另一个答案:您可以实际使用参考资料:

declare -A item=([1, 0]='item1' [1, 1]='1' [1, 2]='20')
...
item01=('item1' '1' '20')
item02=('item2' '4' '77')
item03=('item3' '17' '15')
zeroone=01
zerotwo=02

echo ""
ref="item${zeroone}[@]"
declare -a array=("${!ref}")  ## Still produces 3 arguments as if "${item01[@]}" was called
echo ""
echo "${array[@]}"
echo ""

谢谢,这很有帮助!