在bash中间接引用数组值

时间:2016-10-28 14:26:00

标签: arrays bash reference

我试图在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'或者什么也没有。

3 个答案:

答案 0 :(得分:2)

bash的现代版本采用了ksh功能“ namevars”,非常适合此问题:

#!/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

答案 1 :(得分:1)

您必须在用于间接的变量中编写索引:

anotherArray=("foo" "faa")
foo=("bar" "baz")
faa=("test1" "test2")

for indirect in ${anotherArray[@]}; do
  all_elems_indirection="${indirect}[@]"
  second_elem_indirection="${indirect}[1]"
  echo ${!all_elems_indirection}
  echo ${!second_elem_indirection}
done

如果要迭代anotherArray中引用的每个数组的每个元素,请执行以下操作:

anotherArray=("foo" "faa")
foo=("bar" "baz")
faa=("test1" "test2")

for arrayName in ${anotherArray[@]}; do
  all_elems_indirection="${arrayName}[@]"
  for element in ${!all_elems_indirection}; do
    echo $element;
  done
done

或者,您可以直接将整个间接存储在第一个数组中:anotherArray=("foo[@]" "faa[@]")

答案 2 :(得分:1)

您需要分两步完成

$ for i in ${anotherArray[@]}; do 
     t1=$i[0]; t2=$i[1]; 
     echo ${!t1} ${!t2};  
  done

bar baz
test1 test2