Mowzer Mowzer - 1 year ago 53
Bash Question

Parsing array in Bash

I want to "split" an array (in Bash) to a sub-array while retaining all the array-like properties. Apparently, what I have tried has reduced the array to a string.

A=('foo' 'bar' 'bat' 'baz')
B=${A[@]:0:2} # Get first half of array

for i in ${!B[@]}; do
echo "B[$i]: ${B[$i]}" # result: B[0]: foo bar

The result of this code is:

B[0]: foo bar

But the result I seek is:

B[0]: foo
B[1]: bar

What can I do to retain the array properties in
that will allow me to properly loop thru its elements?

Answer Source
A=('foo 123' 'bar 123' 'bat 123' 'baz 123')
declare -p B


declare -a B='([0]="foo 123" [1]="bar 123")'