2

I'm trying to use a bash for loop to choose an array, the members of which I want to use as variables in a for loop one level down. My issue is in doing the expansion in the second for loop, which I can't figure out.

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

Thank you for any help you can offer!

Luciano
  • 493
  • 5
  • 14
  • What you're looking to do (for purposes of easier searching) is called "indirect array expansion". See [BashFAQ #6](http://mywiki.wooledge.org/BashFAQ/006#Evaluating_indirect.2Freference_variables) -- note that the "nameref" syntax discussed there is available in bash 4.3. – Charles Duffy Jun 02 '17 at 15:23

2 Answers2

3
for name in 'first_two_models[@]' 'second_two_models[@]'; do
    for model in "${!name}"; do
        echo "$model"
    done
done
Nahuel Fouilleul
  • 18,726
  • 2
  • 31
  • 36
2

You need to first build the array reference as a string, then use indirect reference on that string to pull the values:

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
bishop
  • 37,830
  • 11
  • 104
  • 139