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

标签 bash

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

相关文章:

Ruby 到 bash 脚本的翻译

linux - 如何从文本文件中删除换行符?

linux - 从文件名中存在的日期字符串设置文件修改时间

用于特定输出的 Bash 脚本监控程序

shell - 当我打开一个新终端时,我在 .bashrc 中设置的提示颜色不会出现,但只有当我再次获取它时才会出现。我该如何解决?

linux - 使用shell脚本一个接一个地卸载软件

bash - '<&1' 在此脚本中的含义 "read -n 1 k <&1"

reactjs - Yarn 可以列出所有可用的脚本吗?

bash - 在bash脚本中平稳停止inotifywait管道

bash - 是否可以使用 bash 在脚本中直接执行命令?