4

I stripped my use case to these 3 lines (plus the output):

A=(foo bar)
A=$(echo "spam egg")
echo ${A[@]}
spam egg bar

It creates an array with two element written by hand. Then some time later I want to replace my array with the output from a command line tool (e.g. ls *.vhd). Instead of replacing the array, Bash only replaces the first element, so bar gets "attached" at the end.

If I use another handwritten array, then I can't reproduce this behavior.

A=(foo bar)
A=(spam egg)
echo ${A[@]}
spam egg

So I suspect it's related to using $(). How can I solve my problem?

Paebbels
  • 15,573
  • 13
  • 70
  • 139

1 Answers1

5

Use parentheses in the assignment, so that it is treated as an array, rather than one long string with spaces:

A=$(echo "spam egg")
echo ${A[0]}

-> spam egg

A=($(echo "spam egg"))
echo ${A[0]}

-> spam

(The parentheses for $() that tell bash to run a command don't also count for telling it to collect the result as an array.)

Joshua Goldberg
  • 5,059
  • 2
  • 34
  • 39