How to rename an associative array in Bash?

后端 未结 8 2130
感情败类
感情败类 2020-12-08 21:51

I need to loop over an associative array and drain the contents of it to a temp array (and perform some update to the value).

The leftover contents of the first arra

8条回答
  •  失恋的感觉
    2020-12-08 22:40

    Here is a small Copy-Function for bash-Variables of any kind
    - normal scalar variables
    - indexed arrays
    - associative arrays

    ### Function vcp    -VariableCoPy-  
    # $1 Name of existing Source-Variable  
    # $2 Name for the Copy-Target  
    vcp() {
        local var=$(declare -p $1)
        var=${var/declare /declare -g }
        eval "${var/$1=/$2=}"
    }
    

    Usage, Examples:

    # declarations
    var="  345  89  "
    ind_array=(Betty "  345  89  ")
    declare -A asso_array=([one]=Harry [two]=Betty [some_signs]=" +*.<\$~,'/ ")  
    
    # produce the copy
    vcp var varcopy
    vcp ind_array ind_array_copied
    vcp asso_array asso_array_2   
    
    # now you can check the equality between original and copy with commands like
    # declare -p 
    

    The results

    --3    1: "${asso_array[@]}"   
    (5)       asso_array[one]:        |Harry|   
    (11)      asso_array[some_signs]: | +*.<$~,'/ |   
    (5)       asso_array[two]:        |Betty|   
    --3    4: "${asso_array_2[@]}"   
    (5)       asso_array_2[one]:        |Harry|   
    (11)      asso_array_2[some_signs]: | +*.<$~,'/ |   
    (5)       asso_array_2[two]:        |Betty|   
    --2    7: "${ind_array[@]}"   
    (5)       ind_array[0]:   |Betty|   
    (11)      ind_array[1]:   |  345  89  |   
    --2    9: "${ind_array_copied[@]}"   
    (5)       ind_array_copied[0]:   |Betty|   
    (11)      ind_array_copied[1]:   |  345  89  |   
    (11)  11: "$var":   |  345  89  |  
    (11)  12: "$varcopy":   |  345  89  |  
    

提交回复
热议问题