I'm having trouble forming a bash array from a standard output. I've boiled it down to this minimal example:
~$ a=($(echo '1 2 3 "foo bar"'))
~$ echo ${a[0]}
1
~$ echo ${a[1]}
2
~$ echo ${a[2]}
3
~$ echo ${a[3]}
"foo
~$ echo ${a[4]}
bar"
I believe what is happening is that "foo
and bar"
are considered separate items in the standard output, but the goal would be to consolidate those items into one for the array.
Obviously, I could write a small loop to consolidate these terms into one, but I'm wondering of there is a more elegant solution?
EDIT: What goes in place of echo '1 2 3 "foo bar"'
in my code is fairly convoluted, but the point is that I need to form an array from some unknown standard output of this form.
xargs
recognizes quotes so
mapfile -t a <<<"$(echo '1 2 3 "foo bar"' | xargs -n 1)"
printf "%s\n" "${a[@]}"
1
2
3
foo bar