Linux Bash provides a lot of useful features and commands. Pipe or |
is one of them. Bash provides a command-line interface facility which mainly used to concatenate command output to another command.
Linux Bash提供了许多有用的功能和命令。 管道或|
是其中之一。 Bash提供了一个命令行界面工具,主要用于将命令输出连接到另一个命令。
重击管概念 (Bash Pipe Concept)
In Linux everything is file. This may seem odd but it is. Every command executed will have three type of streams which can be used to provide or output data into and from a command.
在Linux中,所有内容都是文件。 这可能看起来很奇怪,但事实并非如此。 每个执行的命令将具有三种类型的流,可用于向命令提供数据或从命令输出数据。
STDIN (0) Standard input where command reads from. In bash default is bash shell
STDIN (0)读取命令的标准输入。 在bash中默认为bash shell
STDOUT (1) Standard output where command output written. In bash default output is bash shell generally.
STDOUT (1)标准输出,其中写入了命令输出。 在bash中,默认输出通常是bash shell。
STDERR (2) Standard error where command errors are written.
STDERR (2)标准错误,其中写入了命令错误。
重击管道的使用 (Bash Pipe Usage)
The pipe will redirect the command STDOUT or standard output into the given next command STDIN or standard input. The syntax is like below. In this example, COMMAND1 output will be feed into COMMAND2 as input.
管道会将命令STDOUT或标准输出重定向到给定的下一个命令STDIN或标准输入。 语法如下。 在此示例中,COMMAND1输出将作为输入馈入COMMAND2。
COMMAND1 | COMMAND2
Now let’s make a simple example. We will use cat
command to print file named names.txt
into command sort
as input.
现在让我们做一个简单的例子。 我们将使用cat
命令将名为names.txt
文件打印到命令sort
作为输入。
$ cat names.txt | sort

管道多个命令(Pipe Multiple Commands)
In the previous example, we have used only one pipe but we can use multiple pipes without a problem to make things better. We just put them in a string like below. In this example, we will pipe commands cat
, sort
and grep
在前面的示例中,我们仅使用了一个管道,但是可以毫无问题地使用多个管道来使事情变得更好。 我们只是将它们放在如下所示的字符串中。 在此示例中,我们将管道命令cat
, sort
和grep
$ cat names.txt | sort | grep "a"

管道到Grep命令(Pipe To Grep Command)
One of the most popular usages of the pipe is with grep
command. We will use multiple grep commands in this example where we will filter line those contains a
and i
letters.
管道最流行的用法之一是使用grep
命令。 在本示例中,我们将使用多个grep命令,其中将过滤包含a
和i
字母的行。
$ cat names.txt | grep "a" | grep "i"

减少管道指令 (Pipe To Less Command)
less
command is another use case for the bash pipe. We generally use cat command to print a file context into less command. In this example, we want to look into the log file of firewalld
.
less
命令是bash管道的另一个用例。 我们通常使用cat命令将文件上下文打印到less命令中。 在此示例中,我们要查看firewalld
的日志文件。
$ cat /var/log/firewalld | less
翻译自: https://www.poftut.com/linux-bash-pipe-command-usage-examples-redirection/