bash 数组数组

srg*_*nch 4 bash array shell-script indexing

试图编写一些嵌套循环,但我不知道如何编写它。也许我看错了方向,但我想写的是:

declare -a bar=("alpha" "bravo" "charlie")
declare -a foo=("delta" "echo" "foxtrot" "golf")

declare -a subgroups=("bar" "foo")
Run Code Online (Sandbox Code Playgroud)

那么我想迭代子组(将来会出现更多barfoo),并在它们内部迭代它们,因为它们可以具有不同数量的元素。

所需的输出类似于:

group name: bar with group members: alpha bravo charlie
        working on alpha of the bar group
        working on bravo of the bar group
        working on charlie of the bar group
group name: foo with group members: delta echo foxtrot golf
        working on delta of the foo group
        working on echo of the foo group
        working on foxtrot of the foo group
        working on golf of the foo group
Run Code Online (Sandbox Code Playgroud)

我写的 closes 代码在barfoo数组中似乎失败了,并且它在每个集合上的元素的扩展中都失败了。

for group in "${subgroups[@]}"; do
   lst=${!group}
   echo "group name: ${group} with group members: ${!lst[@]}"
   for element in "${!lst[@]}"; do
       echo -en "\tworking on $element of the $group group\n"
   done
done
Run Code Online (Sandbox Code Playgroud)

输出是:

group name: bar with group members: 0
        working on 0 of the bar group
group name: foo with group members: 0
        working on 0 of the foo group
Run Code Online (Sandbox Code Playgroud)

Ini*_*ian 6

这是 中一个非常常见的问题bash,要引用数组中的数组,您需要使用declare -n. 后面的名称-n将充当分配的值(在 之后=)的名称 引用。现在我们将这个带有 nameref 属性的变量当作一个数组来扩展,并像以前一样进行完全正确的带引号的数组扩展。

for group in "${subgroups[@]}"; do
    declare -n lst="$group"
    echo "group name: ${group} with group members: ${lst[@]}"
    for element in "${lst[@]}"; do
        echo -en "\tworking on $element of the $group group\n"
    done
done
Run Code Online (Sandbox Code Playgroud)

请注意,bash仅从 v4.3 开始支持 nameref。对于旧版本和其他解决方法,请参阅分配间接/引用变量