Pipes and redirection

  • It is possible to tie the output of one program to the input of another. This is known as a pipe and is created by joining commands using the pipe symbol (|).

  • Pipes are a special form of redirection, which allows you to manage the origin of input streams and the destination of output streams. Redirection syntax for various shells differs slightly. See Table 10-5 for examples of common redirection operators.

    Table 10-5. Common redirection operators

    Redirection function

    Syntax for bash

    Send STDOUT to file.

    $ cmd > file

     

    $ cmd 1> file

    Send STDERR to file.

    $ cmd 2> file

    Send both STDOUT and STDERR to file.

    $ cmd > file 2>&1

     

    $ cmd > file 2> file

    Receive STDIN from file.

    $ cmd < file

    Append STDOUT to file.

    $ cmd >> file

     

    $ cmd 1>> file

    Append STDERR to file.

    $ cmd 2>> file

    Append both STDOUT and STDERR to file.

    $ cmd >> file 2>&1

    Pipe STDOUT from cmd1 to cmd2.

    $ cmd1 | cmd2

    Pipe STDOUT and STDERR from cmd1 to cmd2.

    $ cmd1 2>&1 | cmd2

    Pipe STDOUT from cmd1 to cmd2 while simultaneously writing it to file1 using tee.

    $ cmd1 | tee file1 | cmd2

Get LPI Linux Certification in a Nutshell, 3rd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.