我有以下脚本:
declare -A as1
declare -A as2
declare -a arr=()
declare -A sup
as1[file]="file1"
as2[file]="file2"
echo "test: ${as1[file]} ${as2[file]}"
i=1
arr+=(as$i)
i=2
arr+=(as$i)
for index in "${arr[@]}";
do
declare -n temp="$index"
echo "${temp[file]}"
done
sup[arr]=$arr
echo "try to print:"
for el in "${!sup[@]}"
do
item=${sup[$el]}
for index in "${item[@]}";
do
declare -n temp="$index"
echo "${temp[file]}"
done
done
它基本上构建了一个数组的关联数组。数组中有两个关联数组。 我不确定它是否太复杂,但它应该可以工作。 问题是输出如下:
test: file1 file2
file1
file2
try to print:
file1
最后一行“file2”丢失。我想最后一个循环中有错误,但我无法捕获它。 有什么帮助吗?
sup[arr]=$arr
与 sup[arr]=$arr[0]
是一样的。您只能通过该分配获得数组的第一个元素。 Bash 的数据结构总体上并没有那么强大。数组仅将整数映射到字符串,关联数组仅将字符串映射到字符串。如果不诉诸黑客手段,你就无法将数据结构嵌套在彼此内部。
在这种情况下,您可以将数组的名称存储在
sup
中,并像在其他地方所做的那样使用名称引用。
sup[arr]=arr
# iterating items instead of indices here, if you really
# need the indices then use the ${!sup[@]} logic as you have
for el in "${sup[@]}" ; do
declare -n items="$el"
for item in "${items[@]}" ; do
declare -n temp="$item"
echo "${temp[file]}"
done
done