''cat | tr <file1''——为什么 cat 等待输入而不是从 file1 读取?

''cat | tr <file1'' -- why does cat wait for input instead of reading from file1?

我正在努力重新创建我自己的 shell 从 bash 复制的环境,我发现真实的 bash 有一个非常奇怪的行为:当我输入

cat | tr -d 'o' < file1
(file1 contains only the text "Bonjour")

它输出 Bnjur,所以直到这里没问题,但它一直处于 'waiting for input' 状态,直到我按下回车键。起初我以为是 cattr 执行后在 stdin 上读取,但它的行为不一样,它只是等待用户按下 enter 并且(显然)什么都不做. 我在一些 bash 文档中看到 < 重定向将输入重定向到第一个 SimpleCommand(在第一个管道之前),因此它应该在 cat 上重定向 file1 然后重定向 cat的输出到tr,所以它应该只输出Bnjur,没有别的,那为什么我们必须按回车才能退出命令?

感谢您的帮助。

您正在将输入从文件重定向到 tr,cat 本身没有输入,因此从 stdin 获取输入。试试这个。

cat file1 | tr -d 'o'

< file1 重定向仅适用于 tr 命令,而不适用于整个管道。

所以cat正在从连接到终端的原始标准输入读取。它挂起是因为它在等待您输入内容。

与此同时,tr 正在读取文件。它在处理完文件后退出。

一旦您输入内容,cat 会将其写入管道。由于 tr 已经退出,管道上没有 reader,因此 cat 将收到 SIGPIPE 信号并终止。

如果您希望将重定向应用于 cat,请使用

cat < file1 | tr -d 'o'

如果你想让它应用到整个管道,你可以将它分组在一个子shell中:

( cat | tr -d '0' ) < file1