How to get `for i in $(…)` delimited by lines in bash


get_data() {
  echo foo
  echo "bar baz"

for i in $(get_data); do
   echo "got: $i"

actual output is

got: foo
got: bar
got: baz

what I want is

got: foo
got: bar baz

How do I get the variable i in for i in $(...) to be filled per-line?

>Solution :

Here is how I would do it:

get_data | while read i ; do
  echo "got $i"

The reason why you are not getting what you want with for is that $(get_data) gets expanded by bash to foo bar baz; by default, new lines are treated as word boundaries like space and nothing more. Similarly, using for to loop over contents of a file (for line in $(cat file)) will not work as expected.

P.S. You could modify the IFS (field separator) like this:


as suggested in one of the comments; however I prefer my solution as more explicit and less error-prone.

Leave a Reply Cancel reply