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
You can use bash's indirect expansion for this:
loopOverSomething()
{
looparray="$1[@]"
for i in "${!looparray}"
do
echo "value is $i"
done
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With