Redirecting output using pipes and filters

You can connect two or more commands so that the standard output of one command is used as the standard input of another command. A set of commands connected this way is known as a pipeline.

The connection that joins the commands is known as a pipe. Pipes are useful because they let you tie many single-purpose commands into one powerful command. You can direct the output from one command to become the input for another command using a pipeline. The commands are connected by a pipe (|) symbol.

When a command takes its input from another command, modifies it, and sends its results to standard output, it is known as a filter. Filters can be used alone, but they are especially useful in pipelines. The most common filters are as follows:
  • sort
  • more
  • pg
See the following examples:
  • The ls command writes the contents of the current directory to the screen in one scrolling data stream. When more than one screen of information is presented, some data is lost from view. To control the output so the contents display screen by screen, you can use a pipeline to direct the output of the ls command to the pg command, which controls the format of output to the screen. For example, type the following:
    ls | pg
    In this example, the output of the ls command becomes the input for the pg command. Press Enter to continue to the next screen.

    Pipelines operate in one direction only (left to right). Each command in a pipeline runs as a separate process, and all processes can run at the same time. A process pauses when it has no input to read or when the pipe to the next process is full.

  • Another example of using pipes is with the grep command. The grep command searches a file for lines that contain strings of a certain pattern. To display all your files created or modified in July, type the following:
    ls -l | grep Jul
    In this example, the output of the ls command becomes the input for the grep command.