Search code examples
arraysbash

How to merge two arrays in a zipper like fashion in Bash?


I am trying to merge two arrays into one in a zipper like fashion.

array1=(one three five seven)
array2=(two four six eight)

How do I get this output?

one two three four five six seven eight

I have tried with nested for-loops but can't figure it out. I either get the whole of array2 printed (ex. 12468357) or just the first index like if the loop didn't work (ex. 12325272).


Solution

  • Assuming both arrays are the same size,

    unset result
    for (( i=0; i<${#array1[*]}; ++i)); do
        result+=( "${array1[$i]}" "${array2[$i]}" )
    done