Course contents · Lesson 8 of 19

Linux Pipes and Redirection: Chain Commands Together

The Command Line · Lesson 8 of 19 · 9 min Foundations

You want to know how many files sit in a folder, or which page of a website gets the most visits, and scrolling through hundreds of lines will not tell you. This lesson explains pipes and redirection: the three streams every command has, how to send them to files, how the vertical bar chains commands, and two classic slip-ups.

Three streams: stdin, stdout and stderr

Every process, a running program (lesson 3), starts with three streams: channels that carry text in or out. Each has a name and a number, its file descriptor.

  • Standard input, stdin (0): where a command reads input. By default, what you type in the terminal.
  • Standard output, stdout (1): its normal results. By default, the terminal window.
  • Standard error, stderr (2): its error messages. Also the terminal by default, so errors and results look mixed even though they travel separately.

Redirection changes where a stream goes. The shell, the program that reads your commands (lesson 4), sets it up before the command starts. In the diagram, notice that each stream goes to exactly one place.

A command box with three streams. Stream 0, stdin, comes from the keyboard by default, or from a file with < names.txt. Stream 1, stdout, goes to the screen by default, or with > out.txt into a file that is emptied first, or with >> out.txt onto the end of a file. Stream 2, stderr, goes to the screen by default, or with 2> err.txt into a file. Solid lines are the defaults, dashed lines are redirections
A redirect replaces the default, keyboard or screen; it does not add a second copy.

Redirection: send output to a file, or read from one

> sends stdout into a file. echo hello > out.txt prints nothing: hello went into out.txt in your working directory, the folder you are in. The shell creates the file if it is missing and, if it exists, empties it first, without asking.

>> appends: it adds to the end of the file and keeps what was there, creating the file if needed.

< makes a command read a file as its stdin. wc -l names.txt (wc means word count, and -l asks for lines) prints the line count and the file name. wc -l < names.txt prints only the count, because wc reads stdin and never learns the name.

2> redirects stream 2: ls /nothing 2> err.txt keeps the screen clean and puts the "No such file or directory" message in err.txt. Plain > means 1>. 2> /dev/null throws errors away, since /dev/null discards whatever is written to it (lesson 5).

The vertical bar: one command feeds the next

The vertical bar |, called a pipe, connects the stdout of the command on its left to the stdin of the command on its right. In ls /etc | wc -l, the names in /etc never reach the screen: they flow into wc -l, which counts the lines and prints one number.

This works because ls checks where its output goes: columns in a terminal, but one name per line into a pipe or a file. In the flowchart, follow the error path too.

Flowchart. Command A, ls /etc, writes one name per line to stdout, stream 1. Its output flows through the pipe, a buffer in memory, into stdin, stream 0, of command B, wc -l, which counts the lines. The result goes to the screen by default, as a number such as 212, which is illustrative, or into a file with > count.txt. A dashed line shows errors from ls, stream 2, stderr, skipping the pipe and appearing on the screen. A footer says to add 2>&1 before the bar to send errors through too
Only stdout enters the pipe; error messages go around it to the screen.

The shell starts both commands together. The pipe is a buffer, a small holding area in memory kept by the kernel, the core of the operating system (lesson 2). wc reads lines as soon as ls writes them, and if wc falls behind, ls waits. To save the result, redirect the end of the line: ls /etc | wc -l > count.txt.

Small tools, each doing one job

Each of these commands does one small job and, given no file name, reads stdin, so it can sit anywhere in a chain:

  • sort puts lines in order; -n compares them as numbers and -r reverses the order.
  • uniq merges repeated lines into one, but only repeats that sit next to each other, so you sort first; -c adds a count to each line.
  • head keeps the first 10 lines and tail the last 10; head -n 3 keeps 3.
  • wc -l counts lines.

Suppose access.log is a web server's log, its record of visits, simplified to one page name per visit. Real logs hold more on each line, such as the time, so you would first cut out one column (lesson 9 shows how). The chain in the diagram finds the most visited pages. Watch the lines change at each stage.

Five stages with the lines coming out of each, using an illustrative log of page names. Stage 1, cat access.log, prints /home, /cart, /home, /login, /home, /cart. Stage 2, sort, groups them: /cart, /cart, /home, /home, /home, /login. Stage 3, uniq -c, counts each run: 2 /cart, 3 /home, 1 /login. Stage 4, sort -rn, puts the biggest count first: 3 /home, 2 /cart, 1 /login. Stage 5, head, keeps the first 10 lines, here all 3: the most visited pages
uniq can count the repeats only because sort first put them side by side.

Build your own chains the same way: run the first command, check its output, then add one | command at a time. Here cat only prints the file, so starting with sort access.log gives the same answer.

Two common slip-ups

The bucket is emptied first

> never asks: echo milk > shopping.txt replaces a whole list with one line, where >> would add it. sort names.txt > names.txt even leaves the file empty, because the shell empties it before sort starts reading. Write to a new file instead, then rename it with mv.

Errors do not travel down the bar

The pipe carries only stdout. In ls /nothing | wc -l, the error still appears on screen and wc prints 0, because it received no lines.

Add 2>&1 before the bar to send errors along too. It means "send stream 2 wherever stream 1 goes now", and the & marks 1 as a stream, not a file named 1. ls /nothing 2>&1 | wc -l prints 1, for the error line.

Order matters with files. ls /nothing > all.txt 2>&1 puts both streams in all.txt, but with 2>&1 > all.txt the error stays on screen: stream 2 copied where stream 1 pointed at that moment, the terminal, before stream 1 moved to the file.

Check yourself

After sort names.txt > names.txt, the file is empty. Why, and what should you type instead?

The shell empties names.txt for > before sort starts, so sort reads nothing. Write to a new file, as in sort names.txt > sorted.txt.

ls /nothing | wc -l prints an error message, then 0. Why does wc not count the message?

The message goes to stderr, stream 2, and the pipe carries only stdout, stream 1, so it goes straight to the screen. With 2>&1 before the bar, wc counts it.

Why does uniq -c on an unsorted log list /home more than once?

uniq merges only repeats that sit next to each other, so scattered /home lines form separate runs, each counted alone. Sorting first puts identical lines together.