间接引用bash中的数组值 [英] Indirect reference to array values in bash
本文介绍了间接引用bash中的数组值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图间接引用bash中数组中的值.
I am trying to do an indirect reference to values in an array in bash.
anotherArray=("foo" "faa")
foo=("bar" "baz")
faa=("test1" "test2")
for indirect in ${anotherArray[@]}
do
echo ${!indirect[0]}
echo ${!indirect[1]}
done
这不起作用.我通过回显$ indirect尝试了很多不同的事情来获得$ foo的不同值,但是我只能得到第一个值,所有值,"0"或什么都没有.
This does not work. I tried a lot of differenct things to get the different values of $foo by echoing $indirect but I can only get the first value, all values, '0' or nothing at all.
推荐答案
bash的现代版本采用了ksh功能"namevars",非常适合此问题:
Modern versions of bash adopt a ksh feature, "namevars", that's a perfect fit for this issue:
#!/usr/bin/env bash
case $BASH_VERSION in ''|[123].*|4.[012]) echo "ERROR: Bash 4.3+ needed" >&2; exit 1;; esac
anotherArray=("foo" "faa")
foo=("bar" "baz")
faa=("test1" "test2")
for indirectName in "${anotherArray[@]}"; do
declare -n indirect="$indirectName"
echo "${indirect[0]}"
echo "${indirect[1]}"
done
这篇关于间接引用bash中的数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文