Redirecting Errors with 2>

Su Suriya Ravichandran Updated 06 Dec 2026
7 min read ·Lesson 59 of 205

The operator 2> sends standard error, the channel that carries error messages, to a file. Because standard error is separate from standard output, you can keep a log of problems, hide harmless noise, or store results and errors in different files. This is one of the most useful redirections in everyday scripting.

The Basic Syntax

command 2> file
command 2>> file

The number 2 is the file descriptor of standard error. The operator 2> works like >: it opens the file for writing, creates it if it does not exist and empties it if it does. The operator 2>> appends instead. The examples below use a folder that contains one file, real.txt.

ls real.txt missing.txt 2> errors.txt
echo "errors.txt:"
cat errors.txt

Output:

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

The listing of the existing file still appeared on the screen, because it went to standard output, which was not redirected. The error message was captured in errors.txt.

No Space Between the Number and the Operator

The digit must touch the >. With a space, Bash treats the 2 as an ordinary argument:

ls missing.txt 2 > oops.txt
echo "status: $?"

Output:

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

ls was asked to list two names, missing.txt and 2, and the output redirection > oops.txt captured only its (empty) standard output. Both error messages stayed on the screen. The correct forms are 2> file and 2>file, with the number directly in front of the operator. A space after the > is fine.

Overwriting and Appending

Like >, a single 2> replaces the file each time. The operator 2>> keeps what is there:

ls gone1 2> errors.txt
ls gone2 2> errors.txt
cat errors.txt

Output:

ls: cannot access 'gone2': No such file or directory

Only the second error remains. Now append:

ls gone3 2>> errors.txt
ls gone4 2>> errors.txt
cat errors.txt

Output:

ls: cannot access 'gone2': No such file or directory
ls: cannot access 'gone3': No such file or directory
ls: cannot access 'gone4': No such file or directory

Appending is the right choice for an error log that should collect problems from many runs:

for f in a b; do ls "$f.txt" 2>> multi.txt; done
cat multi.txt

Output:

ls: cannot access 'a.txt': No such file or directory
ls: cannot access 'b.txt': No such file or directory

Separating Results from Errors

You can combine > and 2> on one command to send each stream to its own file:

ls real.txt missing.txt > good.txt 2> bad.txt
echo "good:"
cat good.txt
echo "bad:"
cat bad.txt

Output:

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

The screen stays silent, and each file holds one kind of output. The order of the two redirections does not matter, because they affect different descriptors. This is a handy way to run a long job and review its errors afterward.

Hiding Errors with /dev/null

The special file /dev/null accepts any data and throws it away. Redirecting standard error there hides the messages:

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

Output:

real.txt
status: 2

The error message disappeared, but the exit status is still 2. Hiding a message does not hide the failure, so a script can still check $?.

This technique is common with commands that print many harmless complaints. A search for files across a folder you cannot fully read, for example, produces a permission message for every unreadable folder. Run as an ordinary user:

find /root -name x
find /root -name x 2> /dev/null

Output:

find: '/root': Permission denied

Only the first command printed the message. The second printed nothing, because the message was discarded. Be careful with this habit. Hiding all errors can hide a real problem, such as a mistyped path, so apply 2> /dev/null only to commands where you know the messages are noise.

Checking Whether Any Errors Occurred

When errors go to a file, the file is empty if nothing went wrong. The test -s is true when a file exists and is not empty, so a script can use it to report problems:

ls real.txt 2> clean.txt
ls missing.txt 2> bad2.txt

[ -s clean.txt ] && echo "has errors" || echo "no errors"
[ -s bad2.txt ] && echo "has errors" || echo "no errors"

Output:

no errors
has errors

Note that the file clean.txt was still created, with 0 bytes, because Bash opens the file before the command runs.

Writing Your Own Error Messages

Scripts should send their own error messages to standard error, using >&2. A function is a convenient place to do it:

fail() { echo "error: $*" >&2; return 1; }
fail "bad input" 2> fn.txt
echo "status: $?"
cat fn.txt

Output:

status: 1
error: bad input

The echo inside the function wrote to descriptor 2, so the caller's 2> fn.txt captured it. The message was not on the screen, and the function's return status 1 told the script that it failed. If the caller redirects standard output instead, the message is not captured, and it still shows on the screen:

fail "bad input" > fn2.txt

Output:

error: bad input

The file fn2.txt stayed empty (0 bytes). This is why using the right stream matters: a caller can choose to keep the results and still see the errors, or the other way around.

Errors from the Shell Itself

Some error messages come from Bash, not from the command you wrote. A command that cannot be found is one of them:

nosuchcmd 2> nc.txt
echo "status: $?"
cat nc.txt

Output:

status: 127
bash: nosuchcmd: command not found

Bash looked for the command, failed, and reported the problem on standard error, so 2> nc.txt captured it. The status 127 is the standard code for "command not found". A later lesson on exit codes lists the common values.

There is one case where 2> does not help: when the redirection itself fails. If the target folder does not exist, Bash prints the error for that failure on the screen and does not run the command:

ls missing.txt 2> nodir/e.txt
echo "status: $?"

Output:

bash: nodir/e.txt: No such file or directory
status: 1

Redirecting Errors for a Whole Script or Group

A redirection placed after a group of commands, or after a script call, covers all of them:

{ ls missing.txt; ls nope.txt; } 2> group_err.txt
wc -l < group_err.txt

Output:

2

Both messages were written to the file. The same applies when you run a script:

bash chk.sh 2> chk_err.txt

If chk.sh contains the lines

echo "start"
ls missing.txt
echo "end"

then the screen shows only the normal output while the error goes to the file:

start
end

and chk_err.txt holds:

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

Errors and Pipes

A pipe connects standard output only, so 2> on the first command is needed when you want to hide its errors without affecting the pipe:

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

Output:

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

Both pipelines counted one line, the name real.txt. In the second, the error message still reached the screen, because standard error is not part of the pipe. The words 2> belong to the command they follow, so place it on the command whose errors you want to redirect, not at the end of the pipeline.

Programs That Report Errors Differently

Not every message that looks like an error goes to standard error. Some programs print usage text or warnings on standard output, and some print real errors on standard output, so 2> does not always catch what you expect. When a redirection does not catch a message, test which stream it uses by redirecting each in turn, as in the examples above. The check takes seconds and avoids wrong assumptions in a script.

Where Next

You now know how to move each stream separately. The next lesson shows how to send both streams to the same place, which uses the form 2>&1 and the shortcut &>.

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 Redirecting Errors with 2> and get answers drawn from it.

Signed-in readers only.