Bash Concatenate Arrays
Bash Concatenate Arrays
In Bash scripting, concatenating arrays is useful for various tasks that require combining multiple arrays into a single array.
Syntax
combined_array=(${array1[@]} ${array2[@]})
The basic syntax involves using parentheses and the @
symbol to concatenate the elements of multiple arrays into a single array.
Example Bash Concatenate Arrays
Let's look at some examples of how to concatenate arrays in Bash:
1. Concatenate Two Arrays
This script initializes two arrays, concatenates them, and prints the combined array.
#!/bin/bash
array1=("element1" "element2")
array2=("element3" "element4")
combined_array=(${array1[@]} ${array2[@]})
echo "Combined array: ${combined_array[@]}"
In this script, the array variables array1
and array2
are initialized with elements. The elements of both arrays are concatenated into a new array, combined_array
. The script then prints the combined array.
2. Concatenate Multiple Arrays
This script initializes three arrays, concatenates them, and prints the combined array.
#!/bin/bash
array1=("element1" "element2")
array2=("element3" "element4")
array3=("element5" "element6")
combined_array=(${array1[@]} ${array2[@]} ${array3[@]})
echo "Combined array: ${combined_array[@]}"
In this script, the array variables array1
, array2
, and array3
are initialized with elements. The elements of all three arrays are concatenated into a new array, combined_array
. The script then prints the combined array.
3. Concatenate Arrays with Elements from User Input
This script initializes two arrays with elements from user input, concatenates them, and prints the combined array.
#!/bin/bash
array1=()
array2=()
while true; do
read -p "Enter an element for the first array (or 'done' to finish): " element
if [ "$element" == "done" ]; then
break
fi
array1+=("$element")
done
while true; do
read -p "Enter an element for the second array (or 'done' to finish): " element
if [ "$element" == "done" ]; then
break
fi
array2+=("$element")
done
combined_array=(${array1[@]} ${array2[@]})
echo "Combined array: ${combined_array[@]}"
In this script, the array variables array1
and array2
are initialized as empty arrays. The user is prompted to enter elements for each array, which are added using the +=
operator. When the user types 'done', the loop exits. The elements of both arrays are concatenated into a new array, combined_array
. The script then prints the combined array.
Conclusion
Concatenating arrays in Bash is a fundamental task for combining multiple arrays into a single array in shell scripting. Understanding how to concatenate arrays can help you manage and manipulate arrays effectively in your scripts.