Redirecting Output with > and >>

Su Suriya Ravichandran Updated 06 Dec 2026
8 min read ·Lesson 57 of 205

Redirecting output means telling Bash to send a command's standard output to a file instead of the screen. The operator > writes to a file and replaces whatever was in it, and the operator >> adds to the end of a file and keeps what was there. Together they are how you save results, build log files and generate text files from the command line.

The Basic Syntax

command > file
command >> file

The word after the operator is the name of the file. The command itself is written exactly as before, and its options and arguments do not change. The redirection is an extra instruction to the shell that says where file descriptor 1, standard output, should go.

echo "first" > notes.txt
cat notes.txt

Output:

first

The echo command printed nothing on the screen. Its output was written to notes.txt, and cat showed the contents afterward.

How It Works

The important detail is who does the work. The command never sees the redirection. Bash handles it before the command starts, in these steps:

  1. Bash reads the line and finds the > operator and the file name.
  2. Bash opens the file for writing. If the file does not exist, it is created. If it does exist, it is emptied (truncated) immediately.
  3. Bash connects the open file to file descriptor 1 of the new process.
  4. Bash starts the command, which writes to standard output as usual. The text goes into the file.

Because the file is opened before the command runs, the file exists even if the command prints nothing, and an existing file is emptied even if the command fails. You can see the first step at work when a command lists its own output file:

ls -1 > listing.txt
cat listing.txt

In a folder that held early.txt, fresh.txt, notes.txt and year.txt, the output was:

early.txt
fresh.txt
listing.txt
notes.txt
year.txt

The file listing.txt is in its own listing, because Bash created it before ls started.

Overwriting with >

A single > replaces the contents of the file every time:

echo "first" > notes.txt
echo "second" > notes.txt
cat notes.txt

Output:

second

The text first is gone. Each command with > starts from an empty file. This is the right behavior for a report that should always reflect the latest run, and the wrong behavior for a log that should keep history.

Appending with >>

The >> operator opens the file for appending. The old contents stay, and new output is added at the end:

echo "second" > notes.txt
echo "third" >> notes.txt
echo "fourth" >> notes.txt
cat notes.txt

Output:

second
third
fourth

If the file does not exist, >> creates it, just as > does:

echo "hello" >> fresh.txt
cat fresh.txt

Output:

hello

This makes >> safe to use for a log file that may not exist on the first run.

Saving Command Output

Any command that prints to standard output can be redirected. Some typical uses:

date +%Y > year.txt
ls -1 > listing.txt
printf 'no newline' > nn.txt
printf ' more\n' >> nn.txt
cat nn.txt

Output:

no newline more

The printf command, unlike echo, adds a newline only when you write \n. The first command wrote text with no newline at the end, and the second appended directly after it, so the two pieces joined on one line.

A log file with one line per event is a good use of appending:

echo "$(date +%F) backup done" >> app.log
echo "$(date +%F) cleanup done" >> app.log
cat app.log

Output (the dates are the day you run it; shown here for 21 November 2026):

2026-11-21 backup done
2026-11-21 cleanup done

The $(date +%F) part is command substitution, covered earlier. It inserts the current date in year-month-day form before echo runs.

Emptying a File

A redirection with no command at all creates the file or empties it:

echo "x" > notes.txt
> notes.txt
wc -c < notes.txt

Output:

0

The wc -c command counts bytes, and it reports 0, so the file is empty. Many scripts write the same thing with the colon command, which does nothing and succeeds:

: > notes.txt

Both forms worked in Bash and in Dash. The colon form states the intent more clearly, because a reader sees an explicit command and not just a redirection, and some other shells (Zsh, for example) treat a bare > file differently, so the colon form is the portable choice.

Where the Redirection Can Go

The redirection does not have to be at the end of the line. Bash accepts it before the command too, and the result is the same:

> early.txt echo "written early"
cat early.txt

Output:

written early

Putting the redirection at the end is the usual style and is easier to read. The flexibility matters when you read other people's scripts or when a command is built in several parts.

The Redirection Applies to One Command

A redirection affects only the command it is attached to. The next command on the line, or the next line, prints to the screen again:

echo "one" > only.txt; echo "two"
cat only.txt

Output:

two
one

The two appeared on the screen, and one went into the file.

Redirecting a Group of Commands

To send the output of several commands to one file, wrap them in curly braces or put the redirection after a loop:

for n in 1 2 3; do echo "line $n"; done > loop.txt
cat loop.txt

{ echo "header"; echo "body"; } > group.txt
cat group.txt

Output:

line 1
line 2
line 3
header
body

In the loop example, the file is opened once for the whole loop, so all three lines end up in it. If the redirection were inside the loop as echo "line $n" > loop.txt, each pass would empty the file and only the last line would remain. For loops that add to a file, use >> inside the loop or one > after the done.

Notice the spaces in the braces form: a space after {, and a semicolon (or newline) before }.

Only Standard Output Is Captured

The operator > is short for 1>, which means "redirect file descriptor 1". Standard error is descriptor 2, so it is not affected:

ls nothing.txt > cap.txt

Output:

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

The error message still appeared on the screen, and cap.txt was created but stayed empty (0 bytes). A later lesson in this section shows how to capture standard error. You can write the descriptor number explicitly if you like:

echo "explicit" 1> explicit.txt
cat explicit.txt

Output:

explicit

More Than One Redirection

If you give the same descriptor two destinations, the last one wins, and the earlier file is still created:

echo "both" > one.txt > two.txt
echo "one: $(wc -c < one.txt) two: $(wc -c < two.txt)"

Output:

one: 0 two: 5

The file one.txt was created and left empty. The text both and its newline (5 bytes) went to two.txt. This is rarely useful, but it explains odd results when a line has a stray extra redirection.

When the Redirection Fails

If Bash cannot open the file, it prints an error and does not run the command. The two most common reasons are a missing folder and a target that is a directory:

echo hi > nodir/file.txt
echo "status: $?"
mkdir adir
echo hi > adir
echo "status: $?"

Output:

bash: nodir/file.txt: No such file or directory
status: 1
bash: adir: Is a directory
status: 1

Bash does not create missing folders. Use mkdir -p first when the folder may not exist. The status is 1, and the command, here echo, never ran. The same is true for any other command: after a failed redirection, touch ranflag > nodir/x leaves no ranflag file, because touch was never started.

Permissions cause the same kind of failure. When an ordinary user writes to a file owned by root, Bash reports:

bash: /etc/hostname: Permission denied

The message names the file, not the command, which is a clue that the redirection and not the command failed.

Overwriting Dangers

Because > empties the file before the command runs, reading and writing the same file in one command destroys the data:

printf 'b\na\n' > data.txt
sort data.txt > data.txt
wc -c < data.txt

Output:

0

Bash emptied data.txt first, so sort read an empty file and wrote an empty result. The original text is lost. The same thing happens with cat:

printf 'keep\n' > a.txt
cat a.txt > a.txt
wc -c < a.txt

Output:

0

The safe pattern is to write to a temporary file and then replace the original:

printf 'b\na\n' > data.txt
sort data.txt > sorted.txt && mv sorted.txt data.txt
cat data.txt

Output:

a
b

The && means the mv runs only if sort succeeded. Some commands, such as sort -o data.txt data.txt, have a built-in option for writing to the input file safely, so check the manual of the command first.

Protecting Files with noclobber

Bash has an option called noclobber that makes > refuse to overwrite an existing file. You turn it on with set -o noclobber:

echo "keep me" > precious.txt
set -o noclobber
echo "overwrite" > precious.txt
echo "status: $?"
echo "append ok" >> precious.txt
echo "forced" >| precious.txt
cat precious.txt
set +o noclobber

Output:

bash: precious.txt: cannot overwrite existing file
status: 1
forced

With the option on:

  • > fails on an existing file with the message shown.
  • >> still works, since it does not destroy anything.
  • >| forces an overwrite when you really mean it.

Run set +o noclobber to turn the protection off again. The option only guards against accidental >, so it does not replace careful commands, but it is a useful safety net in an interactive shell.

The echo ... > file pattern is the simplest way to write a file from a script. Writing several lines at once is easier with a here document, covered later in this section. Capturing errors with 2> and combining both streams with 2>&1 are the topics of the following lessons.

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

Signed-in readers only.