How to copy an array in Bash?

后端 未结 8 1929
陌清茗
陌清茗 2020-12-02 15:31

I have an array of applications, initialized like this:

depends=$(cat ~/Depends.txt)

When I try to parse the list and copy it to a new arra

8条回答
  •  执念已碎
    2020-12-02 15:42

    The solutions given in the other answers won't work for associative arrays, or for arrays with non-contiguous indices. Here are is a more general solution:

    declare -A arr=([this]=hello [\'that\']=world [theother]='and "goodbye"!')
    temp=$(declare -p arr)
    eval "${temp/arr=/newarr=}"
    
    diff <(echo "$temp") <(declare -p newarr | sed 's/newarr=/arr=/')
    # no output
    

    And another:

    declare -A arr=([this]=hello [\'that\']=world [theother]='and "goodbye"!')
    declare -A newarr
    for idx in "${!arr[@]}"; do
        newarr[$idx]=${arr[$idx]}
    done
    
    diff <(echo "$temp") <(declare -p newarr | sed 's/newarr=/arr=/')
    # no output
    

提交回复
热议问题