17.13. Pipes

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:

$ cmd1 | cmd2            # cmd1's stdout is cmd2's stdin
$ cat quote
The function of education is to teach one
to think intensively and to think critically.
Intelligence plus character - that is the
goal of true education.

$ cat quote | grep th   # pipe stdout of cat into stdin of grep
                        # (find all lines containing "th")
to think intensively and to think critically.
Intelligence plus character - that is the

$ cat quote | wc        # pipe stdout of cat into stdin of wc
  4      26     160

$ ls
  another
  quote
$ ls | wc               # pipe ls output to wc
  2       2      14     # (number of lines, words, and chars in ls output)

Multiple pipes can be used in the same command line to chain together the stdout into the stdin of a sequence of commands:

cmd one | cmd two | ... | cmd n

Below is an example command line with two pipes. In this example, the stdout of cat is piped into the stdin of grep th, and the stdout of grep th is piped into the input of wc:

$ cat quote | grep th | wc   # number of lines, words, chars in the
  2      14      93          # lines of quote file that contain "th"

Here is the output from the fist pipe in the command above, which shows the output of grep th that is piped into the stdin of wc in the second pipe:

$ cat quote | grep th
to think intensively and to think critically.
Intelligence plus character - that is the

Sometimes you may see the xargs command used in command lines with pipes. The xargs <cmd> command executes cmd on every value passed to it on stdin. We don’t cover xargs in detail, but instead illustrate what it does compared to the ls | wc example shown above.

The example below illustrates the difference between wc and xargs wc as the command after a pipe (ls | wc runs wc on the output of ls whereas ls | xargs wc runs wc on every file listed by ls):

$ ls
  another
  quote
$ ls | wc            # lines, words, chars in ls output
  2       2      14

$ ls | xargs wc      # lines, words, chars in each file listed by ls
  9  53 327 another
  4  26 160 quote
 13  79 487 total

17.13.1. References

For more information see: