How to copy an array in Bash?

Solution 1:

a=(foo bar "foo 1" "bar two")  #create an array
b=("${a[@]}")                  #copy the array in another one 

for value in "${b[@]}" ; do    #print the new array 
echo "$value" 
done   

Solution 2:

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.

Solution 3:

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

Solution 4:

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

This works easily.