我读到写这样的东西很不好,for line in $(command)
相反,正确的方法似乎是:
command | while IFS= read -r line; do echo $line; done
这很好。但是,如果要迭代的是变量的内容而不是命令的直接结果,该怎么办?
例如,假设您创建以下文件quickfox
:
The quick brown
foxjumps\ over -
the
lazy ,
dog.
我希望能够做这样的事情:
# 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