Creating an array in Bash with quoted records from the output of the command

I'm having trouble building a bash array from standard output. I threw it back 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 think that what happens is that "foo, and bar"are treated as separate elements of the standard output, but the aim would be to combine these elements in a single array.

Obviously, I could write a short cycle to combine these terms into one, but I wonder if there is a more elegant solution?

EDIT : what happens instead echo '1 2 3 "foo bar"'in my code is rather confusing, but the fact is that I need to form an array from the unknown standard output of this form .

+4
3

xargs ,

mapfile -t a <<<"$(echo '1 2 3  "foo bar"' | xargs -n 1)"
printf "%s\n" "${a[@]}"
1
2
3
foo bar
+5

, .

a=(1 2 3 "foo bar")

, ,

read a b c d <<<$(echo '1 2 3 "foo bar"')

, , eval.

+5

You can replace

unknown standard output of this kind

in rows and read the lines in the array with the command mapfile.

For example, this can be done using perl and its main module, for example:

some_command() { echo '1 2 3 "foo bar"'; }

echo "output from some_command"
some_command

echo
echo "Parsed into array"
mapfile -t array < <(some_command | perl -MText::ParseWords -lnE 'say for shellwords($_)')
printf '=%s=\n' "${array[@]}"

what prints

output from some_command
1 2 3 "foo bar"

Parsed into array
=1=
=2=
=3=
=foo bar=

EDIT: The just recognized 1_CR answer.

mapfile -t array < <(some_command | xargs -n 1)

much better;)

0
source

All Articles