Combining Standard Output and Standard Error

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

Sometimes you want the results of a command and its error messages in the same place: one log file that tells the whole story, one pipeline that processes everything, or one variable that holds all the text. Bash gives you several ways to merge standard output and standard error. The classic form is 2>&1, and Bash adds the shorter &> and |&.

The examples use a folder with one file, real.txt, and one name that does not exist, missing.txt:

echo 'one' > real.txt

Duplicating a Descriptor with 2>&1

The operator 2>&1 means "make file descriptor 2 point to the same place that file descriptor 1 points to right now". The & in front of the 1 tells Bash that the number is a descriptor, not a file called 1.

To send both streams into one file, combine > and 2>&1:

ls real.txt missing.txt > all.txt 2>&1
cat all.txt

Output:

ls: cannot access 'missing.txt': No such file or directory
real.txt

The screen showed nothing when the first command ran. Both the listing and the error message went into all.txt.

Why the Order Matters

Bash processes redirections from left to right, and each one takes effect immediately. That is why > all.txt 2>&1 works, and the reverse order does not:

ls real.txt missing.txt 2>&1 > partial.txt
cat partial.txt

Output:

ls: cannot access 'missing.txt': No such file or directory
real.txt

The first line of the output came from the first command, on the screen, and partial.txt holds only real.txt. Follow the steps for each form to see why.

For > file 2>&1:

  1. > file points descriptor 1 at the file.
  2. 2>&1 points descriptor 2 at wherever descriptor 1 points now, which is the file.
  3. Both streams go to the file.

For 2>&1 > file:

  1. 2>&1 points descriptor 2 at wherever descriptor 1 points now, which is the terminal.
  2. > file then moves descriptor 1 to the file.
  3. Standard output goes to the file, and standard error stays on the terminal.

The mental model is that 2>&1 copies the current destination of descriptor 1, and does not link the two descriptors permanently. A later change to descriptor 1 does not affect the copy.

The second form is not useless. It is the key to a trick shown later in this lesson: sending only the errors through a pipe.

The Bash Shortcut &>

Bash provides a shorter way to send both streams to a file. The operator &> redirects standard output and standard error together:

ls real.txt missing.txt &> all2.txt
cat all2.txt

Output:

ls: cannot access 'missing.txt': No such file or directory
real.txt

The file holds the same two lines as before. To append instead of overwrite, use &>>:

ls real.txt missing.txt &>> all2.txt
wc -l < all2.txt

Output:

4

Bash also accepts >& file, which means the same as &> file. Most people prefer &> because it reads more clearly, and the Bash manual names it as the preferred form. Both are shortcuts for > file 2>&1.

A Portability Warning

The operators &> and &>> are Bash features. Other shells do not always treat them the same way. In Dash, which is what sh points to on Debian and Ubuntu, &> is not a combined redirection. It is read as & (run in the background) followed by >:

ls missing.txt &> d.txt
echo "after"

Run with dash instead of bash, the first line started ls missing.txt in the background and created an empty d.txt afterward. The error message was shown on the screen, and the file stayed empty:

after
ls: cannot access 'missing.txt': No such file or directory

The order of those two lines can vary, because the background command runs at the same time as echo. For scripts that must run under sh and not only under Bash, write > file 2>&1 instead. It works everywhere.

Appending Both Streams

For a log file that collects everything over many runs, append the standard output and point the standard error to the same place:

echo "run 1" >> run.log
ls missing.txt >> run.log 2>&1
cat run.log

Output:

run 1
ls: cannot access 'missing.txt': No such file or directory

In Bash, ls missing.txt &>> run.log does the same thing in a shorter form.

Sending Both Streams Through a Pipe

A pipe carries only standard output. To pass both streams to the next command, merge them first with 2>&1:

ls real.txt missing.txt 2>&1 | sed 's/^/> /'

Output:

> ls: cannot access 'missing.txt': No such file or directory
> real.txt

The sed command added > to the start of each line, and it processed the error message too. Bash has a shorter form, |&, which means 2>&1 |:

ls real.txt missing.txt |& sed 's/^/| /'

Output:

| ls: cannot access 'missing.txt': No such file or directory
| real.txt

Like &>, the |& operator is specific to Bash and some other modern shells. Use 2>&1 | when portability matters.

Saving and Showing Output with tee

The tee command copies standard input to a file and also passes it on to standard output. Combined with 2>&1, it records everything and shows it at once:

ls real.txt missing.txt 2>&1 | tee both.txt | wc -l
cat both.txt

Output:

2
ls: cannot access 'missing.txt': No such file or directory
real.txt

The count 2 came from wc -l at the end of the pipeline. The file both.txt holds both lines. A later lesson explains tee in detail.

Sending Only the Errors Through a Pipe

Because 2>&1 > /dev/null puts descriptor 2 where descriptor 1 pointed first, which is the pipe, and then sends descriptor 1 to the null device, it passes only the errors on:

ls missing.txt 2>&1 > /dev/null | sed 's/^/err-only: /'

Output:

err-only: ls: cannot access 'missing.txt': No such file or directory

Counting the lines of each form shows the difference:

ls real.txt missing.txt 2>&1 >/dev/null | wc -l
ls real.txt missing.txt >/dev/null 2>&1 | wc -l

Output:

1
0

The first pipeline counted the one error line. In the second, everything was discarded before the pipe, so there was nothing to count. This shows again that the order of > and 2>&1 changes the result.

Discarding Everything

To silence a command completely, send both streams to /dev/null:

ls real.txt missing.txt > /dev/null 2>&1
echo "status: $?"

Output:

status: 2

Nothing was printed, and the exit status 2 is still available. The Bash shortcut ls real.txt missing.txt &> /dev/null behaves the same way. Scripts use this form when they only care about the status, for example to test whether a command exists without any output.

Capturing Both Streams in a Variable

Command substitution captures only standard output by default. To store the error text as well, merge the streams inside the substitution:

out=$(ls real.txt missing.txt 2>&1)
echo "$out"

Output:

ls: cannot access 'missing.txt': No such file or directory
real.txt

Without the 2>&1, the error message would have appeared on the screen when the command ran and would not be in $out.

Redirecting a Group of Commands

To merge the streams of several commands, put the redirections after the group:

{ echo "out"; ls missing.txt; } > grp.txt 2>&1
cat grp.txt

Output:

out
ls: cannot access 'missing.txt': No such file or directory

The same pattern works after a loop's done or after a function call.

Redirecting for a Whole Script

A script can send all of its own output, normal and error, to a log by using exec with redirections at the top. The exec command, when it has no command to run, applies the redirections to the shell itself for the rest of the script:

exec > exe.log 2>&1
echo "this is stdout"
ls missing.txt
echo "done"

When this script runs, nothing appears on the screen. The log file receives:

this is stdout
ls: cannot access 'missing.txt': No such file or directory
done

The pattern is useful for scheduled scripts that run without anyone watching, because everything the script prints ends up in one place. Remember that after the first line there is no output on the terminal at all, so a script that asks the user questions should not use it.

The Order of Lines in the Combined Output

When both streams go to the same file, the lines appear in the order the program wrote them. This script alternates between the two streams:

echo "1 out"
echo "2 err" >&2
echo "3 out"
echo "4 err" >&2

Run with bash mix.sh > mix.txt 2>&1, the file contains:

1 out
2 err
3 out
4 err

The lines kept their order because both descriptors share one open file. Larger programs may buffer their standard output and write it in chunks when it goes to a file, so the interleaving can differ for programs other than echo and the shell itself.

Swapping the Two Streams

With a temporary third descriptor, you can swap standard output and standard error, so that the normal output travels on the error channel and the other way around:

ls real.txt missing.txt 3>&1 1>&2 2>&3 3>&- | sed 's/^/stdout-now: /'

Output:

real.txt
stdout-now: ls: cannot access 'missing.txt': No such file or directory

Read the redirections from left to right:

  1. 3>&1 saves the current standard output (the pipe) as descriptor 3.
  2. 1>&2 points standard output to the terminal, where standard error pointed.
  3. 2>&3 points standard error to the saved pipe.
  4. 3>&- closes descriptor 3, because it is no longer needed.

The listing now reached the screen directly, and the error message went through the pipe, where sed marked it. You will rarely need this, but it shows that the numbered descriptors are real, independent connections that can be copied and moved.

Sending Standard Output to Standard Error

The reverse of 2>&1 is 1>&2 (or >&2), which makes standard output follow standard error. It is the standard way for a script to print a message on the error channel, as in echo "message" >&2. When you combine it with another redirection, the same left-to-right rule applies: echo "to stderr" 1>&2 2> /dev/null first points standard output at the terminal-connected error channel, then discards the error channel itself, so the message still shows on the screen.

Choosing the Right Form

GoalPortable formBash shortcut
Both streams to a file, replacing itcmd > file 2>&1cmd &> file
Both streams appended to a filecmd >> file 2>&1cmd &>> file
Both streams into a pipecmd 2>&1 | nextcmd |& next
Throw everything awaycmd > /dev/null 2>&1cmd &> /dev/null
Only errors into a pipecmd 2>&1 > /dev/null | nextnone

Use the portable forms in scripts that start with #!/bin/sh, and use either style in scripts that start with #!/usr/bin/env bash. Whichever you choose, keep the same form throughout a script so readers do not have to translate between them.

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 Combining Standard Output and Standard Error and get answers drawn from it.

Signed-in readers only.