为什么把文件通过管道传给 echo,它只打印一个空行?

May 30, 2025

假设 note.txt 只有一行,写着 Hello。下面两条命令会打印什么?

cat note.txt | echo         # a blank line
cat note.txt | echo Ready   # Ready

管道(|)把 cat 的输出接到下一条命令的标准输入(stdin)。这是一个可供读取的数据流,读不读取由命令自己决定。正如 Stéphane Chazelas 所说,“echo doesn't read its standard input.”(echo 不读取标准输入。)1

echo 打印的是它的参数,也就是 shell 在命令行上传给它的那些词,最后再打印一个换行符。第一条命令里,echo 收到零个参数,所以你只看到一个换行。第二条里,它收到一个参数 Ready。

echo < note.txt 也是同一个道理。shell 打开文件作为标准输入,echo 收到的参数仍然是零个。试试只改命令名,写成 cat < note.txt。没有文件名参数时,cat 会读取标准输入,于是打印出 Hello。

要把这一行追加到另一个文件,可以让 cat 读取它,再用 >> 将输出写到目标文件末尾。2

cat note.txt >> journal.txt

Footnotes

  1. Chazelas, S. (2013, February 4). Answer to “Redirecting the content of a file to the command ‘echo’”, para. 1. Unix & Linux Stack Exchange. ↩

  2. Ankur. (2012, June 2). Answer to “Shell: read a file and echo it's contents to another file”. Stack Overflow. ↩

© 2025 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2025-05-30). 为什么把文件通过管道传给 echo,它只打印一个空行?. https://caiborui.com/blog/2025-05-30-en-why-echo-ignores-stdin-zhtrans

@misc{borui2025-510d19ee,
  author = {borui},
  title = {{为什么把文件通过管道传给 echo,它只打印一个空行?}},
  year = {2025},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2025-05-30-en-why-echo-ignores-stdin-zhtrans}
}