Connecting commands with pipes

Lesson 23 of 30 · Working with Linux

A pipe (|) connects the stdout of the command on its left to the stdin of the command on its right. The shell arranges the connection; there is no intermediate file to name.

printf 'pear\nplum\npear\n' | grep 'pear' | wc -l

The output is 2, possibly with leading spaces. Trace the data: printf produces three lines, grep selects the two containing pear, and wc -l counts those lines. This counts matching lines, not occurrences; grep here also matches pear inside a longer word.

printf --stdout--> grep --stdout--> wc --stdout--> terminal
                     stderr ----------------------> terminal

A normal pipe carries stdout, not stderr. A diagnostic may therefore still appear on the terminal. The commands may run concurrently, and each must support the input or output interface used. Text streams make many small tools composable, but not every program accepts stdin or produces suitable text.

Status is separate from output

A completed command returns an exit status. Zero conventionally means success; nonzero can mean an error or a command-specific condition such as grep finding no match. $? gives the status of the most recently completed command; read it immediately because another command replaces it.

grep 'pear' /dev/null
printf 'status: %s\n' "$?"

The first command prints no matching line; the second prints status: 1. In a POSIX shell, a pipeline’s status normally comes from its last command, so a successful wc can conceal an earlier failure. Some shells have a pipefail option, but it is not universally available in sh. Inspect individual stages when the distinction matters. first && second runs the second command only if the first succeeds; first; second runs it regardless. These names are illustrative placeholders.