如何在bash中创建列表(或类似列表)的数组? [英] How can I make an array of lists (or similar) in bash?
问题描述
我想遍历bash中的一些列表.现在我有
I want to iterate over a few lists in bash. Right now I have
array=("list1item1 list1item2" "list2item list2item2")
for list in "${array[@]}"
do
for item in $list
do
echo $item
done
done
这不起作用.有什么方法可以在bash中创建列表列表,数组数组或列表数组?
This doesn't work. Is there any way to make a list of lists, array of arrays, or array of lists in bash?
我想遍历list1,然后遍历list1中的listitems.然后遍历list2和list2中的列表项.
I want to iterate over list1, then the listitems in list1. Then iterate over list2, and the list items in list2.
推荐答案
我将缺少的do
和done
添加到您的代码中
Once I added the missing do
and done
into your code:
array=("list1item1 list1item2" "list2item list2item2")
for list in "${array[@]}"
do
for item in $list
do
echo $item
done
done
它产生了预期的输出:
list1item1
list1item2
list2item
list2item2
我不清楚这与您的期望有何不同.
It's not clear to me how this differs from your expectation.
但是,这不是将列表嵌套到数组中的一种非常通用的方法,因为它取决于内部列表是由IFS分隔的. Bash不提供嵌套数组.数组严格来说是字符串数组,仅此而已.
However, that is not a very general way of nesting a list into an array, since it depends on the internal list being IFS-separated. Bash does not offer nested arrays; an array is strictly an array of strings, and nothing else.
您可以使用间接寻址(${!v}
)并将变量名称存储到外部数组中,尽管这有点难看.下面是一个不太丑陋的变体,它依赖于namerefs.它将与相当近期的bash版本一起使用:
You can use indirection (${!v}
) and store variable names into your outer array, although it is a bit ugly. A less ugly variant is the following, which relies on namerefs; it will work with reasonably recent bash versions:
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
这篇关于如何在bash中创建列表(或类似列表)的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!