bash 中的“while read -r line; do ...; done < file` 和 `cat file | while IFS= read -r line; do ...; done` 之间有什么区别吗?

2023-11-29

我正在学习 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

In bash4.2、可以通过使用lastpipe选项,它允许在当前 shell 而不是子 shell 中执行管道中的最后一个命令。

除此之外,使用输入重定向的版本更加高效,因为它不需要启动额外的进程。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

bash 中的“while read -r line; do ...; done < file` 和 `cat file | while IFS= read -r line; do ...; done` 之间有什么区别吗? 的相关文章

随机推荐