How to rename an associative array in Bash?

后端 未结 8 2105
感情败类
感情败类 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:45

    Following both the suggestions of glenn jackman and ffeldhaus, you can build a function which might become handy:

    function cp_hash
    {
        local original_hash_name="$1"
        local copy_hash_name="$2"
    
        local __copy__=$(declare -p $original_hash_name);
        eval declare -A __copy__="${__copy__:$(expr index "${__copy__}" =)}";
    
        for i in "${!__copy__[@]}"
        do
            eval ${copy_hash_name}[$i]=${__copy__[$i]}
        done
    }
    


    Usage:

    declare -A copy_hash_name
    cp_hash 'original_hash_name' 'copy_hash_name'
    


    Example:

    declare -A hash
    hash[hello]=world
    hash[ab]=cd
    
    declare -A copy
    cp_hash 'hash' 'copy'
    
    for i in "${!copy[@]}"
    do
        echo "key  : $i | value: ${copy[$i]}"
    done
    


    Will output

    key  : ab | value: cd
    key  : hello | value: world
    

提交回复
热议问题