遍历数组名称数组,将每个数组名称扩展为其成员 [英] Iterate over array of array names expanding each to its members

查看:85
本文介绍了遍历数组名称数组,将每个数组名称扩展为其成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个由字符串组成的子数组数组,并一次获取主数组中每个子数组的所有子数组值.

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:

这篇关于遍历数组名称数组,将每个数组名称扩展为其成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆