遍历数组的bash,替补数组名动态,这可能吗? [英] Iterate over bash arrays, substitute array name dynamically, is this possible?
本文介绍了遍历数组的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
我收到 22行:$ {$ 2 [@]}:替代不好
推荐答案
您可以使用bash的间接扩张的:
You can use bash's indirect expansion for this:
loopOverSomething()
{
looparray="$1[@]"
for i in "${!looparray}"
do
echo "value is $i"
done
}
这篇关于遍历数组的bash,替补数组名动态,这可能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文