How to Copy an Array in Bash (With Example)


You can use the following syntax to copy an array in Bash:

new_array=("${my_array[@]}")

This particular example will copy the elements of the array named my_array into a new array named new_array.

Note: The quotes within the parentheses are mandatory.

The following example shows how to use this syntax in practice.

Example: How to Copy an Array in Bash

Suppose that we create an array in Bash named my_array that contains the names of various basketball teams:

my_array=(Mavs Hawks Mavs Nets Kings Hawks Lakers)

We can use the following syntax to create a copy of this array named new_array and then view the elements of this new array:

new_array=("${my_array[@]}")

echo "${new_array[@]}"

The following screenshot shows how to use this syntax in practice:

Bash copy array

Notice that when we use the echo statement to view the elements from the new array named new_array we can see that it contains the exact same elements as the original array name my_array.

Note that you could also use the following syntax to print each of the elements in the new array on their own line:

new_array=("${my_array[@]}")

for val in "${new_array[@]}" ; do
echo "$val" 
done 

The following screenshot shows how to use this syntax in practice:

Each of the elements from the array named new_array are now printed on their own line.

Once again we can see that the elements in this array are the same elements from the original array.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Find the Intersection of Two Arrays
Bash: How to Select Random Element from an Array
Bash: How to Iterate Over Associative Array

Leave a Reply