遍历数组名称数组,将每个数组名称扩展为其成员

编程入门 行业动态 更新时间:2024-10-19 18:31:14
本文介绍了遍历数组名称数组,将每个数组名称扩展为其成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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参数扩展.

更多推荐

遍历数组名称数组,将每个数组名称扩展为其成员

本文发布于:2023-07-28 02:35:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1226502.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   名称   遍历   为其   成员

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!