Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

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

like image 949
Jimmy Avatar asked Oct 07 '22 19:10

Jimmy


1 Answers

You can use bash's indirect expansion for this:

loopOverSomething()
{
    looparray="$1[@]"
    for i in "${!looparray}"
    do
        echo "value is $i"
    done
}
like image 179
Gordon Davisson Avatar answered Oct 11 '22 12:10

Gordon Davisson