Using Pipes (|) to Connect Commands

Su Suriya Ravichandran Updated 06 Dec 2026
9 min read ·Lesson 61 of 205

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:

  1. cat fruits.txt writes the six lines to its standard output.
  2. sort reads those lines from its standard input and writes them in alphabetical order, so identical lines end up next to each other.
  3. uniq -c reads the sorted lines and collapses each run of identical lines into one line, prefixed with the count.
  4. sort -rn sorts 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. sort can start reading before cat has 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.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Using Pipes (|) to Connect Commands and get answers drawn from it.

Signed-in readers only.