Pipes and pipelines

Beginner · 5 min

Chain commands with | so each one's stdout feeds the next one's stdin. Stages run concurrently, report only the last status, and need pipefail.

Before thisRedirection

Computerphile · 5 min

Pipes and pipelines

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by ComputerphileReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • cmd1 | cmd2 connects cmd1's stdout straight to cmd2's stdin with no temporary file. A pipeline is a chain of such steps.
  • All stages start at the same time and run concurrently. sleep 1 | sleep 1 took 1 second, not 2.
  • A reader that quits early, like head, makes upstream writers stop. yes | head -3 ends because yes is killed by SIGPIPE, status 141.
  • The pipeline's exit status is that of the last command only. Use ${PIPESTATUS[@]} to see every stage, or set -o pipefail to make a failure anywhere count.
  • Each stage runs in its own subshell, so echo hi | read v leaves v unset in the current shell unless you enable shopt -s lastpipe.

Small tools, joined

Suppose you want to know which IP address hits your server most. There is no command called top-visitors. There is one that picks a column, one that sorts, one that counts duplicates, one that shows the first few lines. Writing a new program for every question would be absurd; so is saving each tool’s output in a temporary file for the next one to read.

A pipe removes the files. The | character connects the stdout of the command on its left to the stdin of the command on its right. The data flows from one process to the next through a small buffer in the kernel. A chain of commands joined this way is a pipeline. The idea is credited to Doug McIlroy and was added to Unix in the early 1970s; that attribution is from memory, and the video discusses it with Brian Kernighan.

Building one in steps

My running data is the web-server log fixture: 200 lines, client address first. Build the pipeline one stage at a time, running it at each step:

$ head -3 logs/access.log
203.0.113.9 - - [2026-11-01T00:00:00Z] "GET / HTTP/1.1" 200 120
10.0.0.5 - - [2026-11-01T01:13:00Z] "GET /login HTTP/1.1" 200 517
192.168.1.20 - - [2026-11-01T02:26:00Z] "GET /static/app.js HTTP/1.1" 200 914
$ cut -d' ' -f1 logs/access.log | head -3
203.0.113.9
10.0.0.5
192.168.1.20

cut -d' ' -f1 keeps the first space-separated field. Add sort, uniq -c to count adjacent duplicates, then a numeric reverse sort:

$ cut -d' ' -f1 logs/access.log | sort | uniq -c | sort -rn | head -3
  40 203.0.113.9
  40 198.51.100.4
  40 192.168.1.20

(My fixture has five addresses, each with exactly 40 hits, so the top three are a tie. Real logs aren’t so flat.) The next lessons teach each of these tools. For now the point is the method: run the left part, look at the output, then add the next stage. Debugging a pipeline is just running a shorter one.

You can break a long pipeline across lines after the |, and Bash continues the command on the next line:

$ cut -d' ' -f9 logs/access.log |
    sort -n |
    tail -1
9116

(Typed interactively, Bash shows a > prompt on the continuation lines. I ran it from a script.) The result is the largest byte count in the log, field 9.

The stages run at the same time

It is easy to picture a pipeline as step one finishing, then step two starting. It isn’t. All the stages are started together, and each blocks until data arrives. I timed two sleep commands:

$ /usr/bin/time -p bash -c 'sleep 1 | sleep 1' 2>&1 | grep real
real 1.01
$ /usr/bin/time -p bash -c 'sleep 1; sleep 1' 2>&1 | grep real
real 2.02

The pipe version took about one second, because both started at once. Think of an assembly line: the second worker starts as soon as the first passes along the first item, instead of waiting for the whole batch. This matters in practice. A pipeline can process a file bigger than memory, because each stage handles a little at a time.

It also means a stage that has all it needs can stop the rest:

$ yes | head -3
y
y
y
$ echo "${PIPESTATUS[@]}"
141 0

yes prints y forever. When head exits after three lines, the pipe has no reader, and the next write from yes kills it with the signal SIGPIPE. A process killed by a signal reports 128 plus the signal number, here 13, giving 141. That is normal and not a bug.

What failed? The exit status problem

A pipeline’s exit status is the status of the last command. Earlier failures vanish:

$ false | true; echo "exit=$?  PIPESTATUS=${PIPESTATUS[*]}"
exit=0  PIPESTATUS=1 0
$ true | false; echo "exit=$?"
exit=1

PIPESTATUS is a Bash array holding every stage’s status, and it must be read immediately, before another command overwrites it. The other fix is the pipefail option, which makes the pipeline’s status the last non-zero status:

$ (set -o pipefail; false | true; echo "pipefail exit=$?")
pipefail exit=1

A later lesson on strict mode explains when to turn it on. Also remember that stderr is not piped: ls missing | wc -l printed the error on screen and a count of 0. Merge it deliberately with 2>&1 | or |& if you want it in the data.

Each stage is a subshell

Every stage of a pipeline runs in its own child process. That surprises people who write ... | read v:

$ echo hi | read v; echo "v=[$v]"
v=[]
$ (shopt -s lastpipe; set +m; echo hi | read v; echo "lastpipe v=[$v]")
lastpipe v=[hi]

The variable was set in a subshell and lost. lastpipe runs the final stage in the current shell instead. It only applies when job control is off, which is why the example has set +m; in a non-interactive script it’s off already. A while read loop at the end of a pipeline has the same limitation, and a later lesson on subshells and process substitution shows the other fix.

Two smaller facts I checked. tee writes its input to a file and also passes it along, so you can save an intermediate stage: ... | tee codes.txt | sort -u. And cat file | wc -l and wc -l < file both gave 200. The cat stage is an extra process for no gain, although it’s harmless.

About the video

Computerphile’s “Unix Pipeline (Brian Kernighan) - Computerphile” was published 13 November 2015 and runs 5 minutes 15 seconds. The description says only that they asked Professor Brian Kernighan what a pipeline is. It has English subtitles, so I’m confident it is in English. I couldn’t read the transcript, so I can’t say which examples he uses or whether he touches on concurrency or exit status; those sections are mine. It is more about the idea and history than the shell syntax. Nir Lichtman’s 3-minute video is a more practical second view.

What I did not run

Linux. Pipe buffer limits (I pushed 200000 bytes through yes | head -c 200000 | wc -c and got all 200000, which shows nothing about the buffer size), named pipes beyond a single mkfifo that carried a word.

Next

A pipeline is only as good as its first stage. The next lesson covers looking at text: viewing text with cat, less, head and tail.

Check yourself

  1. 01false | true returns status 0. Why, and how do you make the failure visible?

    The pipeline's status is the last command's, and true succeeded. Check ${PIPESTATUS[@]} right afterwards, or run set -o pipefail so a failing stage makes the whole pipeline fail.

  2. 02Does sleep 1 | sleep 1 take about one second or two?

    About one. Both stages start together and run at the same time. I measured 1.01 seconds against 2.02 for sleep 1; sleep 1.

  3. 03Why does yes | head -3 stop instead of running forever?

    When head exits, the pipe has no reader, and the next time yes writes it gets SIGPIPE and dies. The shell reports yes with status 141.

  4. 04After echo hi | read v, why is $v empty?

    read ran in a subshell for that pipeline stage, and its variable died with it. shopt -s lastpipe (in a script, or with job control off) runs the last stage in the current shell.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark