我正在尝试使用bash for循环来选择一个数组,我希望将其成员用作for循环中的变量一级。我的问题是在第二个for循环中进行扩展,我无法弄清楚。
first_two_models=( model_one model_two )
second_two_models=( model_three model_four )
for name in first_two second_two; do
for model in ${"$name_models"[@]}; do
echo $model
done
done
感谢您提供任何帮助!
答案 0 :(得分:3)
for name in 'first_two_models[@]' 'second_two_models[@]'; do
for model in "${!name}"; do
echo "$model"
done
done
答案 1 :(得分:2)
您需要首先将数组引用构建为字符串,然后对该字符串使用间接引用来提取值:
first_two_models=( model_one model_two )
second_two_models=( model_three model_four )
for name in first_two second_two; do
array="${name}_models[@]" # build reference as string
for model in "${!array}"; do # use indirect reference to access
echo "$model"
done
done