DEV Community

Cover image for How a Linux Pipe Passes One Command's Output to Another
Labby for LabEx

Posted on Originally published at labex.io

How a Linux Pipe Passes One Command's Output to Another

Originally published on LabEx Blog.

A pipe lets one command hand its output directly to the next command. It is useful when the first command produces more text than you need, and the next command can select, transform, or inspect that text.

This short LabEx video follows a six-line order file through a simple pipeline. The goal is not to create a temporary file: it is to make the first command's standard output become the second command's standard input.

A flow diagram showing cat orders.txt sending standard output through a pipe to head -n 3, producing the first three of six lines.

Start with two separate commands

In the example, orders.txt contains six lines. Reading it with cat prints every line:

cat orders.txt
Enter fullscreen mode Exit fullscreen mode

To read only the first three lines directly from that file, use head:

head -n 3 orders.txt
Enter fullscreen mode Exit fullscreen mode

Those commands do different jobs. cat writes text to standard output. head -n 3 can read text from a file, but it can also read text supplied on standard input.

Put a pipe between them

Use the vertical bar to connect the commands:

cat orders.txt | head -n 3
Enter fullscreen mode Exit fullscreen mode

The shell starts the commands as one pipeline. Instead of sending the output from cat to the terminal, it connects that output to the input of head. head receives all six lines, prints the first three, and then the result appears in the terminal.

The file itself is not changed. Run cat orders.txt again and all six original lines are still there.

Read the command from left to right

When a pipeline feels confusing, name the connection rather than memorizing the punctuation:

  1. cat orders.txt produces text.
  2. | carries that text to the next command.
  3. head -n 3 reads the incoming text and keeps the first three lines.

That model also helps you spot a common mistake: type both sides before pressing Enter. The pipe is part of one command line, not a second command you run afterward.

Try it in a Linux environment

Start with the Quick Start with Linux course on LabEx to practice terminal navigation and reading files. Then create a small text file of your own and change the number after -n to see how the selected output changes.

For the full walkthrough, watch Connect Commands with a Pipe.

Top comments (0)