Using Pipes (|) to Connect Commands
A pipe connects the standard output of one command to the standard input of the next command. It is the feature that turns a collection of small tools, each doing one job, into a program you assemble on the spot. Where a redirection such as > connects a command to a file, a pipe connects a command to another running command, and no file is involved.
The examples use two small files. fruits.txt holds six lines, and app.log holds four log lines:
printf 'apple\nbanana\ncherry\napple\nbanana\napple\n' > fruits.txt
printf 'ERROR disk full\nINFO ok\nERROR timeout\nWARN slow\n' > app.log
Understanding the Concept
The previous lessons showed that every command has three standard streams: standard input (descriptor 0), standard output (descriptor 1) and standard error (descriptor 2). A pipe uses the first two. Whatever the left-hand command writes to its standard output becomes the standard input of the right-hand command.
Most text tools in Linux read from standard input when they are not given a file name. That design is what makes pipes useful: sort, uniq, wc, grep, head, tail, tr and cut all behave the same on a file or on a stream, so they can be placed after any command that produces text.
Syntax
command1 | command2 | command3
The vertical bar | sits between commands. Spaces around it are optional but make the line easier to read. A sequence of one or more commands joined by pipes is called a pipeline.
Basic Example
Count how many times each fruit appears in fruits.txt, most frequent first:
cat fruits.txt | sort | uniq -c | sort -rn
Output:
3 apple
2 banana
1 cherry
Understanding the Example
Each command in the pipeline does one small job:
cat fruits.txtwrites the six lines to its standard output.sortreads those lines from its standard input and writes them in alphabetical order, so identical lines end up next to each other.uniq -creads the sorted lines and collapses each run of identical lines into one line, prefixed with the count.sort -rnsorts the result again, this time numerically (-n) and in reverse (-r), so the largest count comes first.
No temporary files were created. The uniq command only collapses adjacent duplicates, which is why the first sort is required. Without it, the three apple lines would not be next to each other.
The first stage could also be written without cat, since sort accepts a file name: sort fruits.txt | uniq -c | sort -rn gives the same result with one fewer process.
How It Works Internally
When Bash sees a pipeline, it asks the operating system for a pipe: a small in-memory buffer with a write end and a read end. Bash then starts every command in the pipeline as its own process, and it connects the write end of each pipe to the standard output of the command on its left and the read end to the standard input of the command on its right.
Two consequences follow from this design:
- The commands run at the same time, not one after another.
sortcan start reading beforecathas finished. Data flows through the pipe as it is produced, and the buffer holds it between the two processes. If the buffer is full, the writer waits. If it is empty, the reader waits. - Each command is a separate process. That detail matters for variables, as a later section shows.
You can see the connection on a running system. The standard input of the last command in a pipeline is a pipe, not a file or a terminal:
printf 'x\n' | ls -l /proc/self/fd/0
On Linux the link points to something like pipe:[428]. The number differs on every run.
Pipes Carry Only Standard Output
A pipe takes standard output only. Standard error is not part of it and still goes to the terminal:
ls fruits.txt nofile.txt | wc -l
Output:
ls: cannot access 'nofile.txt': No such file or directory
1
The error message was printed by ls straight to the screen. The count 1 came from wc -l, which saw only the single name fruits.txt that ls wrote to standard output.
To send both streams through the pipe, merge standard error into standard output first, as shown in the previous lesson:
ls fruits.txt nofile.txt 2>&1 | wc -l
Output:
2
Now wc -l received both lines, the error message and the file name. In Bash, |& is a shorter way of writing 2>&1 |.
Pipelines Stop Early When the Reader Is Finished
Because the commands run at the same time, a command on the right can finish before the command on the left. The command yes prints the letter y forever, yet this pipeline ends immediately:
yes | head -n 3
Output:
y
y
y
After head has printed three lines it exits and closes its end of the pipe. The next time yes tries to write, the operating system sends it a SIGPIPE signal, which ends it quietly. This is how a pipeline can process the beginning of a huge or endless stream without reading the rest of it.
Building Pipelines Step by Step
Long pipelines are easiest to write one stage at a time. Run the first command and look at its output, add the next stage and look again, and continue. For example, to list the error messages in app.log without the word ERROR:
grep ERROR app.log
ERROR disk full
ERROR timeout
Add a stage that keeps the second field:
grep ERROR app.log | cut -d' ' -f2
disk
timeout
Add a stage that counts the lines instead:
grep ERROR app.log | wc -l
2
Each stage was checked before the next one was added, so a mistake is easy to locate.
Splitting a Long Pipeline Over Several Lines
When a line ends with a pipe, Bash knows the command is not finished and continues reading on the next line. This keeps long pipelines readable:
printf 'b\na\nb\n' |
sort |
uniq -c
Output:
1 a
2 b
Put the pipe at the end of the line, not at the start of the next one. A line that begins with | is a syntax error.
The Exit Status of a Pipeline
A pipeline runs several commands, but it reports one exit status: by default, the status of the last command. A failure earlier in the pipeline is hidden:
false | true
echo "status: $?"
Output:
status: 0
The command false failed, but true succeeded, so the pipeline as a whole reports success. Bash keeps the individual statuses in the array PIPESTATUS, which must be read immediately, before another command runs:
false | true
echo "PIPESTATUS: ${PIPESTATUS[*]}"
Output:
PIPESTATUS: 1 0
If you want the pipeline to fail when any stage fails, turn on the pipefail option. The status then becomes the status of the last command that failed:
set -o pipefail
false | true
echo "pipefail status: $?"
set +o pipefail
Output:
pipefail status: 1
Later lessons on exit codes (116 and 117) and on strict mode (120) return to this option. For now, remember that without it, $? after a pipeline describes only the last command.
A pipeline can be negated with !. The exit status is then reversed:
! false | false
echo "neg status: $?"
Output:
neg status: 0
The pipeline false | false returns 1, and the ! turns that into 0.
Pipes Run Their Commands in Subshells
Because every command in a pipeline is a separate process, a command like while read on the right side of a pipe runs in a subshell, a child copy of the shell. Variables it changes are lost when the pipeline ends:
count=0
printf 'a\nb\nc\n' | while read -r line; do count=$((count+1)); done
echo "count after pipe loop: $count"
Output:
count after pipe loop: 0
The loop did run three times, but it incremented its own copy of count. The original variable in the main shell was never touched.
There are two common ways to keep the changes. The first is to feed the loop from a process substitution instead of a pipe, so that the loop runs in the current shell:
count=0
while read -r line; do count=$((count+1)); done < <(printf 'a\nb\nc\n')
echo "count after process substitution: $count"
Output:
count after process substitution: 3
The second is to do all the work that needs the variable inside the same group, in the subshell, and use the result there:
total=0
seq 1 5 | { while read -r n; do total=$((total+n)); done; echo "total inside group: $total"; }
echo "total outside: $total"
Output:
total inside group: 15
total outside: 0
Bash also offers the option shopt -s lastpipe. It runs the last command of a pipeline in the current shell, which keeps its variables, but it only has an effect when job control is off, as it is in scripts. A later lesson covers process substitution in detail (151).
Reading from a Pipe with read
The same subshell behavior explains why read at the end of a pipe seems to do nothing:
echo "hello world" | read first second
echo "first='${first:-}' second='${second:-}'"
Output:
first='' second=''
The read command ran in a subshell and assigned first and second there. With lastpipe the assignment reaches the current shell:
shopt -s lastpipe
echo "hello world" | read first second
echo "first='${first:-}' second='${second:-}'"
shopt -u lastpipe
Output:
first='hello' second='world'
A here string, introduced in lesson 64, is the usual portable-to-Bash alternative: read -r first second <<< "hello world".
Using Pipelines in Conditions
A pipeline is a command, so its exit status can drive an if statement. This is a common pattern with grep -q, which prints nothing and only reports whether it found a match:
if printf 'abc\n' | grep -q b; then echo "found"; fi
if printf 'abc\n' | grep -q z; then echo "found"; else echo "not found"; fi
Output:
found
not found
Lesson 66 introduces if in full.
Pipes and Arguments: xargs
A pipe delivers data on standard input, but some commands expect their input as arguments. The command xargs bridges the two by reading lines from standard input and building a command line from them:
printf 'one\ntwo\n' | xargs -I{} echo "item: {}"
Output:
item: one
item: two
The -I{} option tells xargs to run the command once per input line and to replace {} with that line. A later lesson (112) combines xargs with find -print0 for file names that contain spaces.
Practical Applications
Pipes appear in almost every useful shell command. A few typical forms:
echo "Hello World" | tr 'a-z' 'A-Z'
HELLO WORLD
printf '10 b\n9 a\n100 c\n' | sort -n
9 a
10 b
100 c
The second example shows why the -n option matters. Without it, sort compares the lines as text, and 10 comes before 9:
printf '10 b\n9 a\n100 c\n' | sort
10 b
100 c
9 a
The Bash shell itself works the same way with every tool in this tutorial. Later lessons on text processing (106 to 109) build on the pipeline shape of producer | filter | filter | consumer, and the next lesson shows how to save the data flowing through the middle of a pipeline with tee.