且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-05 11:47:04

为循环的控制变量(即 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: