我正在学习 bash,我在互联网上找到了一个教程,说它们是相同的:
while read -r line;
do
...
done < file
$ cat file | while IFS= read -r line;
do
...
done
这两个循环有什么细微差别吗?它们真的是一样的吗?
最佳答案
最大的区别在于,在管道中,while
循环在子 shell 中执行,因此如果您更改 while
主体中的任何变量的值,这些将在管道完成后丢失。
$ foo=5
$ cat file | while IFS= read -r line; do
> foo=$line # assume $line is not 5
> done
$ echo $foo
5
$ while IFS= read -r line; do
> foo=$line
> done < file # Assume one line with the word foo
$ echo $foo
foo
在 bash
4.2 中,这可以通过使用 lastpipe
选项来缓解,它允许管道中的最后一个命令在当前 shell 而不是子 shell 中执行.
除此之外,使用输入重定向的版本效率更高,因为它不需要启动额外的进程。
关于bash - "while read -r line; do ...; done < file` 和 `cat file | while IFS= read -r line; do ...; done` 之间的 bash 有什么区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26471631/