说明
本文是个人学习用的非官方中英对照译文,原文:https://diveintosystems.org/book/Appendix2/pipe.html。
原书采用 CC BY-NC-ND 4.0 许可(禁止演绎),请勿公开传播本译文。
标为「译注」「现代更新」的内容是译者补充,不代表原书作者观点;代码与原文逐字一致,未作改动。
17.13. Pipes
管道让用户能在一条命令行中把一串命令连接起来。管道(|)把管道(|)之前列出的命令的 stdout 重定向到管道之后列出的命令的 stdin:
Pipes allow a user to link together a sequence of commands in a single command line. A pipe (|) redirects the stdout of the command listed before the pipe (
|) to the stdin of the command listed after the pipe:
1 | $ cmd1 | cmd2 # cmd1's stdout is cmd2's stdin |
1 | $ cat quote |
同一条命令行中可以使用多个管道,把一串命令的 stdout 和 stdin 依次串接起来:
Multiple pipes can be used in the same command line to chain together the stdout into the stdin of a sequence of commands:
1 | cmd one | cmd two | ... | cmd n |
下面是一个带有两个管道的命令行例子。在这个例子中,cat 的 stdout 被管道输送到 grep th 的 stdin,而 grep th 的 stdout 被管道输送到 wc 的输入:
Below is an example command line with two pipes. In this example, the stdout of
catis piped into the stdin ofgrep th, and the stdout ofgrep this piped into the input ofwc:
1 | $ cat quote | grep th | wc # number of lines, words, chars in the |
下面是上面命令中第一个管道的输出,它展示了 grep th 的输出,这个输出在第二个管道中被输送到 wc 的 stdin:
Here is the output from the first pipe in the command above, which shows the output of
grep ththat is piped into the stdin ofwcin the second pipe:
1 | $ cat quote | grep th |
有时你可能会看到在带管道的命令行中使用 xargs 命令。xargs <cmd> 命令对通过 stdin 传给它的每一个值执行 cmd。我们不详细介绍 xargs,而是把它的作用与上面的 ls | wc 例子做一个对比。
Sometimes you may see the
xargscommand used in command lines with pipes. Thexargs <cmd>command executescmdon every value passed to it on stdin. We don’t coverxargsin detail, but instead illustrate what it does compared to thels | wcexample shown above.
下面的例子说明了在管道之后使用 wc 与 xargs wc 作为命令的区别(ls | wc 对 ls 的输出运行 wc,而 ls | xargs wc 对 ls 列出的每个文件运行 wc):
The example below illustrates the difference between
wcandxargs wcas the command after a pipe (ls | wcrunswcon the output oflswhereasls | xargs wcrunswcon every file listed byls):
1 | $ ls |
17.13.1. 参考资料
17.13.1. References
更多信息参见:
For more information see:
- Pipelines from the Bash Reference Manual from gnu.org.
- cheat-sheets.org 上的最常用的 Unix 命令
- most used Unix commands from cheat-sheets.org