Bash array expansion using variable indirection expansion

前端 未结 2 377
礼貌的吻别
礼貌的吻别 2020-12-21 15:12

I am trying to expand all values in an array I get to through indirect expansion:

> my_array=(coconut banana)
> echo \"${my_array[@]}\" 
coconut banana         


        
相关标签:
2条回答
  • 2020-12-21 16:04

    This should work

    my_array_name='my_array[@]'
    echo "${!my_array_name}"
    

    After comment : you have to create a string with the name of the array and '[@]', another example

    my_array_name="$1"'[@]'
    echo "${!my_array_name}"
    

    After comment : test in a function

    display_elem() {
      local arrname
      arrname="$1[@]"
      printf "%s\n" "${!arrname}"
    }
    
    display_elem my_array
    
    0 讨论(0)
  • 2020-12-21 16:04

    The problem is my_array_name=my_array. You need to retrieve all values of my_array. Try this instead:

     my_array_name=${my_array[@]}
     echo "${my_array_name[@]}"
    
    0 讨论(0)
提交回复
热议问题