我想创建一个由字符串组成的子数组数组,并一次获取主数组中每个子数组的所有子数组值.
I'd like create an array of subarrays made of strings, and get all the subarray values at once for each subarray in the main array.
例如,我希望获得"str1""str2" 进行第一次打印,但实际上它会打印出"sub1"
For example, I'm hoping to get "str1" "str2" to print out the first time, but instead it actually prints out "sub1"
#!/bin/bash declare -a arr=(sub1 sub2) declare -a sub1=("str1" "str2") declare -a sub2=("str3" "str4") for item in "${arr[@]}"; do echo $item done我想要这种行为,因此以后可以调用脚本并通过"str1""str2" 转换为带有两个值的参数.然后,我想再次使用"str3"运行脚本." str4"
I want this behavior so I can later call a script and pass "str1" "str2" to an argument that takes two values. Then I'd like to run the script again with "str3" "str4"
推荐答案为循环的控制变量(即 item )设置 nameref 属性,以便可以在循环体中用作对由其值指定的变量的引用.
Set the nameref attribute for the loop's control variable (i.e. item), so that it can be used in the loop body as a reference to the variable specified by its value.
declare -n item for item in "${arr[@]}"; do echo "${item[@]}" done或者,按照 Ivan的建议,您可以在每个名称后附加 [@] 在控制变量上使用间接扩展.
Alternatively, as Ivan suggested, you can append [@] to each name and use indirect expansion on the control variable.
for item in "${arr[@]/%/[@]}"; do echo "${!item}" done有关更多信息,请参见:
For further information, see:
- 声明内置,
- Shell参数,
- Shell参数扩展.
更多推荐
遍历数组名称数组,将每个数组名称扩展为其成员
发布评论