Iterate over array of array names expanding each to its members

微笑、不失礼 提交于 2021-02-07 08:16:45

问题


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.

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 

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"


回答1:


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

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:

  • declare built-in,
  • Shell Parameters,
  • Shell Parameter Expansion.



回答2:


A few more variants beside of what @oguzismail suggested, first:

declare -a sub1=("str1" "str2")
declare -a sub2=("str3" "str4")
declare -a arr=("${sub1[*]}" "${sub2[*]}")

for item in "${arr[@]}"; do
  echo $item
done

Second:

declare -a arr=(sub1 sub2)
declare -a sub1=("str1" "str2")
declare -a sub2=("str3" "str4")

for item in "${arr[@]}"; do
  name="$item[@]"
  echo "${!name}"
done


来源:https://stackoverflow.com/questions/63350479/iterate-over-array-of-array-names-expanding-each-to-its-members

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!