How to copy an array in Bash? How to copy an array in Bash? arrays arrays

How to copy an array in Bash?


a=(foo bar "foo 1" "bar two")  #create an arrayb=("${a[@]}")                  #copy the array in another one for value in "${b[@]}" ; do    #print the new array echo "$value" done   


The simplest way to copy a non-associative array in bash is to:

arrayClone=("${oldArray[@]}")

or to add elements to a preexistent array:

someArray+=("${oldArray[@]}")

Newlines/spaces/IFS in the elements will be preserved.

For copying associative arrays, Isaac's solutions work great.


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 newarrfor idx in "${!arr[@]}"; do    newarr[$idx]=${arr[$idx]}donediff <(echo "$temp") <(declare -p newarr | sed 's/newarr=/arr=/')# no output