I read that it is bad to write things like for line in $(command)
, the correct way seem to be instead:
command | while IFS= read -r line; do echo $line; done
This works great. But what if what I want to iterate on is the contents of a variable, not the direct result of a command?
For example, imagine that you create the following file quickfox
:
The quick brown
foxjumps\ over -
the
lazy ,
dog.
I would like to be able to do something like this:
# This is just for the example,
# I could of course stream the contents to `read`
variable=$(cat quickfox);
while IFS= read -r line < $variable; do echo $line; done; # this is incorrect