Search code examples
arraysbashconcatenation

How do I combine two arrays into a third array?


I have two arrays: array1 and array2:

array1=( a b c )
array2=( 1 2 3 )

How do I make a third array, array3:

array3=( a b c 1 2 3 )

This question is different from Combine arrays in the beginning of a for-loop (Bash) because this deals exclusively with combining arrays, not whether such a statement is legal within a for loop.

This question is different from Merging two Bash arrays into key:value pairs via a Cartesian product because I'm just trying to concatenate two arrays rather than combine them in a key:value style.


Solution

  • From The Advanced Bash Scripting Guide example 27-10, with a correction:

    declare -a array1=( zero1 one1 two1 )
    declare -a array2=( [0]=zero2 [2]=two2 [3]=three2 )
    dest=( "${array1[@]}" "${array2[@]}" )
    echo "${dest[@]}"
    zero1 one1 two1 zero2 two2 three2
    

    Thus, for my case, it's:

    array3=( "${array1[@]}" "${array2[@]}" )