Iterate over bash arrays, substitute array name dynamically, is this possible?

bash

Solution

You can use bash's indirect expansion for this:

loopOverSomething()
{
    looparray="$1[@]"
    for i in "${!looparray}"
    do
        echo "value is $i"
    done
}

Problem

I have a script that iterates over an array of values, something like this (dumbed down for the purposes of this question) : ``` COUNTRIES=( ENGLAND SCOTLAND WALES ) for i in ${COUNTRIES[@]} do echo "Country is $i " done ``` My question is, is it possible to substitute the array dynamically? For example, I want to be able to pass in the array to iterate over at runtime. I've tried the following but I think my syntax might be wrong ``` COUNTRIES=( ENGLAND SCOTLAND WALES ) ANIMALS=( COW SHEEP DOG ) loopOverSomething() { for i in ${$1[@]} do echo "value is $i " done } loopOverSomething $ANIMALS ``` I'm getting `line 22: ${$2[@]}: bad substitution`

Original source