How to Copy an Array in Bash [6 Simple Methods]

LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now

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

  1. Using @ within the expression ${array[@]: copied_array=("${old_array[@]}")
  2. Using * within the expression ${array[*]: copied_array=("${old_array[*]}")
  3. By appending array: copied_array+=("${old_array[@]}")
  4. Using array slicing for a partial copy: sliced_copy=(${old_array[@]:start:count})
  5. Using the mapfile command: mapfile -t copied_array <<<"${old_array[@]}"
  6. Using for loop: for element in "${old_array[@]}"; do
    copied_array+=("$element"); done

To copy an array in Bash is to make a duplicate array that is the exact copy of the original array. This involves copying the array elements to a new array-type variable and is particularly significant when it comes to working with the array data but without altering the original array. This article discusses 6 effective methods of how to copy an array in Bash including mentioning standard syntax and Bash scripts. Moreover, it shows the copying process of an associative array in Bash.

6 Ways to Copy an Array in Bash

Copying arrays is a common operation in Bash facilitating data manipulations without affecting the source array ensuring data integrity and data handling flexibility. This section introduces 6 simple yet effective methods regarding how to copy an array in Bash. It mentions array expression syntax, array appending, for loop, and the mapfile command to copy a Bash array. Additionally, it sheds light on the array slicing technique to copy a specific part of an array when necessary in Bash.

1. Using ${array[@]} Expression

The simplest method to copy a Bash array is to use the expression  ${array[@]} with the assignment operator, (=). The syntax is copied_array=("${old_array[@]}") and it expands the old_array elements and stores them in the copied_array to make a copy. Here’s an example:

#!/bin/bash

#declare array
old_array=('Debian' 'Red hat' 'Ubuntu' 'Suse')

#array expansion and copy
clone_array=("${old_array[@]}")

#print the 2 Array
echo "original_array: ${old_array[@]}"
echo
echo "copied_array: ${clone_array[@]}"
EXPLANATION

In the script, after declaring the old_array using old_array=('Debian' 'Red hat' 'Ubuntu' 'Suse'), the code clone_array=("${old_array[@]}") copies old_array to clone_array by expanding each element and storing them in the clone_array which is evident after printing both the original and copied array.

bash copy array with @ notation

2. Using ${array[*]} Expression

The asterisk (*) notation is also capable of copying a Bash array when used in the expression ${array[*]} within the complete syntax array_copy=("${original_array[*]}"). Below is an example to copy a Bash array using ${array[*]} expression:

#!/bin/bash

#declare array
food=('apple' 'banana' 'pie' 'orange')

#array expansion and copy using * sign 
food_clone=("${food[*]}")

#print the 2 Arrays to verify copy operation 
echo "original_array: ${food[@]}"
echo
echo "copied_array: ${food_clone[@]}"
EXPLANATION

In the script, the food_clone=("${food[*]}") expression expands the array food as a single string using ${food[*]} and copies the array to the duplicate array food_clone by storing elements as a string. Finally, the echo command prints the 2 arrays to verify that the array has been copied.

bash copy array with * notation
Note: The above expression ${array[*]} expands the array like ${array[@]} but with a difference. It treats all the array elements as a single string to expand and copy the array rather than treating them as individual entities like ${array[@]}  

3. By Appending to Another Array

Append to an array in Bash is to add a new element to the end of the array using the shorthand operator +=. Now, the “+=” operator within the syntax copied_array+=("${old_array[@]}") easily appends the entire old_array to the copied_array which eventually copies the Bash array. Here’s how:

#!/bin/bash

#the original array
old_array=("Batman" "IronMan"  "Spiderman")

#creating empty array to copy old_array
clone_array=()

#copy old_array to clone_array
clone_array+=("${old_array[@]}")

#print the arrays
echo "original Array:${old_array[@]}"
echo
echo "copied Array:${clone_array[@]}"
EXPLANATION

The above script first declares two arrays named old_array (full with 3 elements) and clone_array (empty) using old_array=("Batman" "IronMan"  "Spiderman") and clone_array=(). Then the notation clone_array+=("${old_array[@]}") appends the entire old_array to the clone_array; eventually making a copy of the old_array.

append to array and copy the array in BashAs you can see, the above script copies a Bash array by appending it to another array.

4. Using “for” Loop

The Bash for loop is a powerful tool to copy an array in Bash through the process of iterating over an array and storing the values in another array variable to make a copy of the original array.

Let’s see an example to see for loop in action to copy an array in Bash:

#!/bin/bash

# Original array
old_array=("apple" "banana" "cherry")

# Initialize an empty array for copying
clone_array=()

# Iterate over the original array and copy to the new array
for element in "${old_array[@]}"; do
    clone_array+=("$element")
done

# Display the original and copied arrays
echo "Original Array: ${old_array[@]}"
echo "Copied Array: ${clone_array[@]}"
EXPLANATION

In the script above, after creating an indexed array named old_array with 3 elements, the loop for element in "${old_array[@]}" iterates over the old_array and stores the element in another array clone_array. This iterative approach finally makes a copy of the old_array named clone_array and this is strongly visible after printing the arrays using the echo command.

using for loop to copy array Terminal output states that the for loop successfully copies an array in Bash.

5. Using the “mapfile” Command

The mapfile command (also called readarray) is a handy tool for copying an array in Bash. It is generally used to read lines from a specified standard input into an array variable and assigning an array as its input seamlessly lets the mapfile command copy an array. Here’s how to copy a Bash array using the “mapfile” command:

#!/bin/bash

#Original array
old_array=("Apple" "Orange" "Banana")

#Copy array using mapfile
mapfile -t clone_array <<<"${old_array[@]}"

#Print the arrays
echo "Original Array: ${old_array[@]}"
echo "Copied Array: ${clone_array[@]}"
EXPLANATION

The above script first initializes an array named old_array with 3 elements: Apple Orange Banana using old_array=("Apple" "Orange" "Banana"). Then the mapfile command reads lines from its standard input (which is an array in this case) and assigns them to a duplicate array named clone_array. The -t flag ensures that each element from the original array is assigned to the clone_array to a separate index. Finally, the echo command prints the arrays and verifies the copy operation.

bash copy array with mapfileAs you see in the above image, the mapfile command successfully copies an array in Bash.

Note: If you do not use the -t flag, the array elements will be accidentally stored as a single string to the first index of the clone_array which might not be the desired result. So, be cautious while copying a Bash array using the “mapfile” command 

6. Using Array Slicing for Partial Copy

Apart from copying an entire array in Bash, copying an array with a specific range of elements might become necessary in data handling and manipulation within arrays. Here, the array slicing technique is a handy tool to partially copy an array in Bash using the syntax  arr_copy_sliced=(${old_array[@]:start:count}).

Here’s an example to partially copy an array in Bash using array slicing:

#!/bin/bash

old_array=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'kali')

#copy array to another array variable but with array slicing 
arr_copy_sliced=(${old_array[@]:1:3})

#print the arrays

echo "original array:${old_array[@]}"
echo "sliced_array_copy: ${arr_copy_sliced[@]}"
EXPLANATION

In this script, after the declaration of the old_array with 5 items using old_array=(‘Debian’ ‘Red hat’ ‘Ubuntu’ ‘Suse’ ‘kali’), the array slicing notation ${old_array[@]:1:3} begins to slice the array from index 1 (Red hat) and continues till it has sliced 3 elements (Red hat Ubuntu Suse) from the old_array. The sliced array is stored by the array-type variable arr_copy_sliced and this effectively copies only partially the old_array to the array arr_copy_sliced. Finally, the copying of the array using the slicing technique is visible after printing the original and copied array.

array slicing to copy arrayThe array slicing method takes an array of 5 elements and copies it partially considering only 3 elements.

Copy an Associative Array in Bash

In Bash, it’s possible to copy an associative array apart from the indexed array and that too using the for loop. See the below example to copy a Bash associative array using for loop:

#!/bin/bash

# Original associative array
declare -A original_array
original_array=([key1]="value1" [key2]="value2" [key3]="value3")

# Copy the associative array using a loop
declare -A copied_array
for key in "${!original_array[@]}"; do
    copied_array["$key"]="${original_array["$key"]}"
done

# Display the original and copied associative arrays
echo "Original Associative Array Values: ${original_array[@]}"
echo "Original Keys: ${!original_array[@]}"
echo
echo "Copied Keys: ${!copied_array[@]}"
echo "Copied Associative Array Values: ${copied_array[@]}"
EXPLANATION

The above script declares an associative array using declare -A original_array and initializes its key-value pairs with original_array=([key1]="value1" [key2]="value2" [key3]="value3"). Then the loop for key in "${!original_array[@]}" iteratively takes each key of the original_array and stores the corresponding key-value pairs to the copied_array. Finally, after printing the arrays, it’s clear that the for loop successfully copies a Bash associative array.

copy associative array in BashThe above states the success of copying an associative array in Bash using for loops.

Conclusion

This article discusses the concepts of 6 effective methods of how to copy an array in Bash. It sheds light on the methods of array appending, array iterations with for loops, the mapfile command, and array slicing to copy Bash arrays to another array variable. Furthermore, it shows how to copy a Bash associative array using for loop. Hope this guide clears your vision on copying Bash arrays ensuring smooth handling and validation of data within arrays without the modification of the source array data.

People Also Ask

How to copy a Bash array using the assignment operator?

To copy an array in Bash using the assignment operator, (=), use the syntax new_array=(“${old_array[@]}”). This will expand the elements of the old_array and store them in the new_array variable to make a copy. For instance, copy_car=("$CARS{[@]}") will copy the array CARS to the copy_car array.

What is it meant by copying a Bash array?

Copying an array in Bash means creating a new array containing the same elements as an existing one. This involves duplicating the values of an array to another array and allowing users to work with another instance of the same array without modifying the original. Use the syntax new_array=("${old_array[@]}") to simply copy the old_array to another array called new_array.

Can I copy a specific portion of an array in Bash?

Yes, you can. Use the array slicing technique to fetch specific elements from a large array and store them in another array type variable to copy a specific portion of an array in Bash. The syntax to use is sliced_copy=(${original_array[@]:start:count}) which copies elements of original_array from the start index to elements defined by count. For instance, using the syntax sliced=(${main[@]:1:4}) will copy 4 elements of the main array starting from index 1 and store them in the slice array.

What is the difference between @ and * notations in copying a Bash array?

The @ notation within the ${array[@]} expression treats each element of the array as “separate words” when copying the array to another array. It ensures that the elements separated by spaces are preserved as distinct entities. On the other hand, the * notation in the expression ${array[*]} treats the entire array as a single stream of string to copy it to another array. It concatenates all the array elements into a single string regardless of spaces.

How to copy the values of an associative array in Bash?

To copy the values of an associative array in Bash, use the notation ${assoc_array[@]} to extract all the values and assign them to a new array with the complete syntax copied_values=(${assoc_array[@]}). In addition, you can use the syntax copied_keys=(${!assoc_array[@]}) to copy only the keys of an associative array to another array.

Related Articles


<< Go Back to Array Operations in Bash | Bash Array | Bash Scripting Tutorial

Rate this post
Md Masrur Ul Alam

Assalamu Alaikum, I’m Md Masrur Ul Alam, currently working as a Linux OS Content Developer Executive at SOFTEKO. I completed my Bachelor's degree in Electronics and Communication Engineering (ECE)from Khulna University of Engineering & Technology (KUET). With an inquisitive mind, I have always had a keen eye for Science and Technolgy based research and education. I strongly hope this entity leverages the success of my effort in developing engaging yet seasoned content on Linux and contributing to the wealth of technical knowledge. Read Full Bio

Leave a Comment