Dynamic variable names for an array in bash

有些话、适合烂在心里 提交于 2020-01-11 07:17:10

问题


I have an array called "loop".

For each element in "loop" I want to create an array whose name contains the text of the current element.

I then want to loop through each new array and print every element from each array.


This post seems to have a good solution for variables but I do not know how to adapt it to work for arrays.


My Script

#!/bin/bash
loop=(
first
second
third
)

for word in "${loop[@]}"    
do
        declare "${word}_holder=( hello world )"
        var="${word}_holder"
        echo "$var"
        for i in "${!var}[@]"
        do
                echo "$i"
        done
done

Current output

first_holder
( hello world )[@]
second_holder
( hello world )[@]
third_holder
( hello world )[@]

Desired Output

first_holder
hello
world
second_holder
hello
world
third_holder
hello
world

回答1:


It ain't pretty, but it's a start:

#!/bin/bash
loop=(
first
second
third
)

for word in "${loop[@]}"    
do
    var=${word}_holder
    eval "declare -a ${var}"
    eval "${var}=( Hello World )"
    eval 'nEntries=${#'${var}'[@]}'
    echo ${var}
    for (( ii=0; ii<$nEntries; ii++ )); do
       cmd='echo ${'${var}'['$ii']}'
       eval ${cmd}
    done
done



回答2:


for word in "${loop[@]}"; 
do 
   name="${word}_holder";
   declare -a "$name"; 
   declare -n arr="$name";
   echo $name;
   arr=(hello world);
   arr_ref="$name[@]";
   for w in "${!arr_ref}";
   do 
      echo $w; 
   done; 
done;                             

first_holder                                                                                                                              
hello                                                                                                                                     
world                                                                                                                                     
second_holder                                                                                                                             
hello                                                                                                                                     
world                                                                                                                                     
third_holder                                                                                                                              
hello                                                                                                                                     
world     

Of course there is no point of doing all this if you are not going to refer to the dynamically generated arrays (first_holder, etc) ever.



来源:https://stackoverflow.com/questions/44379252/dynamic-variable-names-for-an-array-in-bash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!