Indirect reference to array values in bash

后端 未结 3 1525
清歌不尽
清歌不尽 2020-12-12 01:35

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          


        
相关标签:
3条回答
  • 2020-12-12 01:57

    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
    
    0 讨论(0)
  • 2020-12-12 02:18

    You need do it in two steps

    $ for i in ${anotherArray[@]}; do 
         t1=$i[0]; t2=$i[1]; 
         echo ${!t1} ${!t2};  
      done
    
    bar baz
    test1 test2
    
    0 讨论(0)
  • 2020-12-12 02:20

    You have to write the index in the variable used for indirection :

    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
    

    If you want to iterate over every element of every arrays referenced in anotherArray, do the following :

    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
    

    Alternatively you could directly store the whole indirections in your first array : anotherArray=("foo[@]" "faa[@]")

    0 讨论(0)
提交回复
热议问题