Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

#!/bin/bash

get_data() {
  echo foo
  echo "bar baz"
}

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Here is how I would do it:

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

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:

IFS=$'\n'

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading