【问题标题】:How can I make an array of lists (or similar) in bash?如何在 bash 中创建一组列表(或类似列表)?
【发布时间】:2017-06-17 09:28:42
【问题描述】:

我想在 bash 中遍历几个列表。现在我有

array=("list1item1 list1item2" "list2item list2item2")

for list in "${array[@]}"
do
    for item in $list
    do
        echo $item
    done
done

这不起作用。有没有办法在 bash 中制作列表列表、数组数组或列表数组?

我想遍历 list1,然后遍历 list1 中的列表项。然后遍历list2,以及list2中的列表项。

【问题讨论】:

  • 您对“不工作”的定义是什么?我按照预期的顺序得到 4 行输出。您的方法存在问题,但对于示例数据,它似乎有效。

标签: arrays bash list loops


【解决方案1】:

缺乏对 rici 发表评论的声誉......

现在可以或多或少地创建列表列表,并避免在 rici 的回答(从 bash4.4 及更高版本)中为此使用名称引用,这要归功于数组引用扩展:@Q。例如:

declare -a list1=("one" "two three")
declare -a list2=("four five" "six")
declare -a listOfLists=("(${list1[*]@Q})" "(${list2[*]@Q})")
echo "${#listOfLists[@]}"
2

如您所见,listOfLists 正确扩展为 2 个元素。现在好消息是,感谢@Q,listOfLists 中的列表元素也将正确扩展为每个元素 2 个(而不是不使用 @Q 时的 3 个元素):

declare -a sameAsList1="${listOfLists[0]}"; declare -a sameAsList2="${listOfLists[1]}"
echo "${#sameAsList1[@]}" ; echo "${#sameAsList2[@]}"
2
2
declare -p sameAsList1 && declare -p list1
declare -a sameAsList1=([0]="one" [1]="two three")
declare -a list1=([0]="one" [1]="two three")

我们终于得到了列表列表!

【讨论】:

    【解决方案2】:

    一旦我将缺少的 dodone 添加到您的代码中:

    array=("list1item1 list1item2" "list2item list2item2")
    
    for list in "${array[@]}"
    do
        for item in $list
        do
            echo $item
        done
    done
    

    它产生了预期的输出:

    list1item1
    list1item2
    list2item
    list2item2
    

    我不清楚这与您的预期有何不同。

    但是,这不是将列表嵌套到数组中的一种非常通用的方式,因为它依赖于 IFS 分隔的内部列表。 Bash 不提供嵌套数组;数组严格来说是字符串数组,仅此而已。

    您可以使用间接 (${!v}) 并将变量名称存储到外部数组中,尽管它有点难看。下面是一个不那么丑陋的变体,它依赖于 namerefs;它适用于相当新的 bash 版本:

    array=(list1 list2)
    list1=("list 1 item 1" "list 1 item 2")
    list2=("list 2 item 1" "list 2 item 2")
    for name in "${array[@]}"; do
      declare -n list=$name
      for item in ${list[@]}; do
        echo "$item"
      done
    done
    

    输出:

    list 1 item 1
    list 1 item 2
    list 2 item 1
    list 2 item 2
    

    【讨论】:

      猜你喜欢
      • 2017-01-17
      • 2011-03-19
      • 2017-10-09
      • 2010-10-01
      • 1970-01-01
      • 2010-10-02
      • 2020-09-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多