我正在寻找一种干净的方式(没有 eval 命令)来间接引用数组。这是我想要的更准确的描述:
function valueof {
echo "indirection1 \$$1=${!1}"
eval "echo indirection2 \\\$$1=\${$1[@]}" # Untill this step its fine.
# My final objective is to do this (but eval is not a very sexy solution) :
for i in $(eval "echo \${$1[@]}") ; do
echo $i
done
# Here is the "problem", ie. "bad substitution"
echo "indirection3 \$$1=${!1[@]}"
# "1[@]" is evaluated first i guess?
}
使用以下值调用:
a=("a" "aa" "aaa")
b=("b" "bb" "bbb")
valueof a
valueof b
我的输出是:
indirection1 $a=a
indirection2 $a=a aa aaa
a
aa
aaa
indirection1 $b=b
indirection2 $b=b bb bbb
b
bb
bbb
在 stderr 上:
prog.sh: line 10: indirection3 $1=${!1[@]}: bad substitution
prog.sh: line 10: indirection3 $1=${!1[@]}: bad substitution
感谢您对此问题的回答/评论:)