Dynamic variable names for an array in bash

前端 未结 2 2037
醉酒成梦
醉酒成梦 2021-01-06 23:11

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 l

2条回答
  •  北恋
    北恋 (楼主)
    2021-01-07 00:06

    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.

提交回复
热议问题