Here is how I would do it:
get_data | while IFS= read -r 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.