Mowzer Mowzer - 7 months ago 14
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.

myscript.sh

#!/bin/bash
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
done


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
B
that will allow me to properly loop thru its elements?

Answer
A=('foo 123' 'bar 123' 'bat 123' 'baz 123')
B=("${A[@]:0:2}")
declare -p B

Output:

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