Shell Pipelines: Connecting Commands Through Pipes

Most Unix tools do one small job: grep selects lines, sort orders them and wc counts them. The shell lets you join such tools on a single command line, so a question such as how many distinct addresses appear in a log takes one line instead of a program. This lesson shows how the shell wires the tools together, which data flows between them and how to tell whether the whole chain succeeded.

How a pipe connects two processes

When you type grep ERROR app.log | sort | wc -l, the shell starts three processes at once and joins them with the | operator. The result is a pipeline: a sequence of commands in which each command's standard output becomes the next command's standard input. Every process begins with three open file descriptors: 0 for standard input, 1 for standard output and 2 for standard error. For each | the shell creates a pipe, attaches its write end to descriptor 1 of the command on the left and attaches its read end to descriptor 0 of the command on the right.


Shell
command1 | command2 | command3


Three boxes labelled grep ERROR, sort and wc -l joined left to right by pipe arrows, with dashed standard error arrows from each box down to a terminal box.


A pipe is a fixed-size buffer inside the kernel, 64 KiB by default on Linux. The stages run concurrently: a writer that fills the buffer pauses until the reader drains it, and a reader facing an empty pipe waits for data. When every writer has closed its end, the reader sees EOF and can finish. Some filters, such as sort, must read their entire input before writing a single line; others, such as grep, pass each line on as soon as they have processed it. If a reader quits early, as head -n 1 does, the upstream command's next write triggers SIGPIPE, which stops it quietly.



Building a pipeline from filters

Most stages are filters: programs that read lines on standard input, transform them and write the result to standard output. Because every filter speaks the same plain-text interface, you can build a pipeline one stage at a time, run it, read the output and only then add the next stage. Order matters: uniq removes only adjacent duplicate lines, so it almost always follows sort.


Example: To count the distinct customers in the second column of a comma-separated file, extract the column, sort it, drop duplicates and count what is left.


Shell
cut -d, -f2 orders.csv | sort | uniq | wc -l


The table compares the ways a command's two output streams can travel.


Syntax

Reaches the next command

Goes elsewhere

a \| b

standard output of a

standard error to the terminal

a 2>&1 \| b

standard output and standard error

nothing

a \|& b (Bash)

standard output and standard error

nothing

a \| tee log \| b

standard output of a

a copy of that output in the file log

a > file

there is no next command

standard output into file



Exit status and subshells

Every command finishes with an exit status, an integer where 0 means success and any other value signals a failure or a negative result, such as grep finding no match. By default a pipeline reports only the status of its last command, so a failure in an earlier stage goes unnoticed. Bash's pipefail option, enabled with set -o pipefail, changes the rule:


status={snbyĀ defaultrightmostĀ nonzeroĀ si,Ā orĀ 0Ā ifĀ allĀ areĀ 0withĀ pipefail\text{status} = \begin{cases} s_n & \text{by default} \\ \text{rightmost nonzero } s_i \text{, or } 0 \text{ if all are } 0 & \text{with pipefail} \end{cases}


Here s1,…,sns_1, \dots, s_n are the stage statuses from left to right. Bash also records every stage's status in the PIPESTATUS array, which you must read immediately, because the next command overwrites it.


Each stage runs in its own process, a subshell in Bash. Variables set inside a stage therefore vanish when it ends:


Shell
count=0
printf 'a\nb\nc\n' | while read -r line; do count=$((count + 1)); done
echo "$count"    # prints 0


The loop increments its own copy of count. Redirecting a file into the loop instead, as in while read -r line; do ...; done < lines.txt, keeps the loop in the current shell.

What to remember

  • A pipeline joins each command's standard output to the next command's standard input, and all stages run at the same time.
  • Standard error bypasses a plain |; use 2>&1 | or |& to send it down the pipe.
  • Sort before uniq, because uniq collapses only adjacent duplicates.
  • By default a pipeline's status is its last command's; set -o pipefail reports the rightmost failure, and PIPESTATUS holds every stage's status.
  • Variables changed inside a pipeline stage do not survive in the parent shell.

Example: Tracing a log-analysis pipeline

You are on call and want quick answers from app.log. Each line holds a time, a level, a component and a message, separated by single spaces:


Plain text
09:00:01 INFO auth login ok
09:00:04 ERROR db timeout
09:00:09 INFO web request served
09:00:12 WARN auth slow token check
09:00:15 ERROR auth bad password
09:00:21 INFO db query ok
09:00:30 ERROR db timeout
09:00:33 INFO web request served
09:00:41 ERROR web upstream reset
09:00:47 INFO auth logout


Every command below chains filters: programs that read lines on standard input and write transformed lines to standard output. Trace the data stage by stage before revealing each solution.


a) Run grep ERROR app.log | cut -d' ' -f3 | sort | uniq -c. What does each stage pass on, and what is the final output?


grep ERROR keeps only the lines containing ERROR, the ones stamped 09:00:04, 09:00:15, 09:00:30 and 09:00:41, so it passes ________ lines into the pipe.


cut -d' ' -f3 splits each line at spaces and keeps field 3, the component. It still emits ________ lines, in file order: db, auth, db, web.


sort reorders them alphabetically to auth, db, db, web, so the first line it writes is ________.


uniq -c collapses each run of identical adjacent lines into one line and prefixes the length of the run. The final output is three lines (GNU uniq pads each count with leading spaces):

  • 1 auth
  • 2 db
  • 1 web

b) A colleague deletes the sort stage and runs grep ERROR app.log | cut -d' ' -f3 | uniq -c. How many lines does it print, and why is the result misleading?


The input to uniq -c is now db, auth, db, web in file order. Comparing neighbours, db and auth differ, auth and db differ, and db and web differ, so the number of adjacent identical pairs is ________.


With nothing to collapse, uniq -c prints 4 lines, each with a count of 1: 1 db, 1 auth, 1 db, 1 web. The two db errors are reported separately, so db appears to have one error when it had two. uniq merges only neighbouring lines; sorting first makes all equal lines neighbours.


c) Which component wrote the most lines overall? Run cut -d' ' -f3 app.log | sort | uniq -c | sort -rn | head -n 1.


cut extracts all ten components. Counting them, auth appears at 09:00:01, 09:00:12, 09:00:15 and 09:00:47, four times; db appears at 09:00:04, 09:00:21 and 09:00:30, ________ times; web appears at 09:00:09, 09:00:33 and 09:00:41, ________ times. The counts add to 10, matching the file.


After sort | uniq -c the stream is 4 auth, 3 db, 3 web. The second sort -rn orders lines numerically (-n) in reverse (-r), so the largest count comes first, and head -n 1 keeps only that line.


The output is 4 auth: auth wrote the most lines, 4 of the 10.


d) You run these two lines in a fresh Bash shell, then again after set -o pipefail. What does the second line print each time?


Shell
grep FATAL app.log | wc -l
echo $?


No line contains FATAL, so grep writes nothing and wc -l counts and prints ________. That is a successful count, so wc exits with status 0, while grep exits with status ________ because it matched no line.


Without pipefail, the pipeline's status is the status of its last stage, wc, so echo prints 0. With pipefail set, the status is the rightmost nonzero stage status, which is grep's, so echo prints 1. In both runs the PIPESTATUS array, read straight after the pipeline, would hold 1 0.

Match each term used when building Unix shell pipelines with the description that defines it. Each description belongs to exactly one term.

Match each term
A.

A kernel buffer that carries one process's output into another process's input

B.

A command that copies its standard input both to a file and to standard output

C.

A Bash option that makes a chain of commands report the rightmost nonzero exit status of its stages

D.

A program that reads lines on standard input, transforms them and writes the result to standard output

E.

A Bash array holding the exit status of every stage of the most recent chain of commands

F.

File descriptor 2, used for diagnostics and not passed on by a plain bar between commands

pipefail

Filter

Pipe

tee

Standard error

PIPESTATUS

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A Bash command must print north|south and pass that line to tr, which replaces the literal pipe character with a colon. In the command template below, OPERATOR is a placeholder for one shell operator.


Shell
printf '%s\n' 'north|south' OPERATOR tr '|' ':'


Complete both blanks: replace OPERATOR with , and the single output line, excluding its terminating newline, is .

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

The file fruits.txt contains the nine lines below, in this order. You run uniq fruits.txt | wc -l in a Unix shell. What number does the command print? Give a whole number.


Plain text
apple
pear
apple
apple
fig
pear
fig
fig
kiwi

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice