【问题标题】:Indirect reference to array values in bashbash 中对数组值的间接引用
【发布时间】:2016-10-28 14:26:00
【问题描述】:

我正在尝试在 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'或什么都没有。

【问题讨论】:

标签: arrays bash reference


【解决方案1】:

现代版本的 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

【讨论】:

    【解决方案2】:

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

    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[@]")

    【讨论】:

    • 好的,我认为可能有一种更优雅的方法来执行此操作,而不是将数组的每个值分配给单独的变量以在循环中使用它。谢谢!
    【解决方案3】:

    你需要分两步完成

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

    【讨论】:

    • 这不完全是两个步骤,他可以设置anotherArray=("foo[@]" "faa[1]") 并且间接将访问特定元素而不仅仅是第一个。
    • 是的,可以有无限多的变化,但这不是 OP 所要求的。
    猜你喜欢
    • 2015-02-11
    • 1970-01-01
    • 2020-09-10
    • 1970-01-01
    • 2017-01-09
    • 2011-06-02
    • 2014-07-05
    • 1970-01-01
    相关资源
    最近更新 更多