← Back to Bash Course | Chapter 8: Input/Output & Redirection | Lesson 6 of 13

Redirection Operators

Redirection operators let a script send its output to a file instead of the screen, or pull input from a file instead of the keyboard.

Writing and Overwriting with >

The > operator sends a command's stdout to a file, creating it if needed and completely truncating it if it already exists. Every run of the same > command wipes out the previous contents.

Warning: > destroys existing file contents instantly with no confirmation.

Example: Writing and Overwriting with >

bash
#!/bin/bash
echo "first line" > out.txt
echo "second run overwrites" > out.txt
cat out.txt
rm -f out.txt

Appending with >>

The >> operator appends output to the end of a file instead of truncating it, creating the file if it does not already exist. This is the safe choice for log files that should accumulate over time.

Example: Appending with >>

bash
#!/bin/bash
echo "line 1" > log.txt
echo "line 2" >> log.txt
echo "line 3" >> log.txt
cat log.txt
rm -f log.txt

Reading Input from a File with <

The < operator redirects a file's contents to a command's stdin, as though the file's text had been typed. This works with any command that reads from stdin, including read and cat.

Example: Reading Input from a File with <

bash
#!/bin/bash
echo "data from a file" > input.txt
read -r line < input.txt
echo "Read: $line"
rm -f input.txt

Redirecting stderr and Combining Streams

2> sends only stderr to a file, leaving stdout untouched. &> (or > file 2>&1) sends both streams to the same destination, which is convenient for capturing everything a command produces.

Note: &> is a bash extension; POSIX sh scripts should use > file 2>&1 instead.

Example: Redirecting stderr and Combining Streams

bash
#!/bin/bash
ls not_a_real_file 2> errors.txt
echo "stderr captured:"
cat errors.txt
rm -f errors.txt

{ echo out; echo err >&2; } &> combined.txt
echo "combined captured:"
cat combined.txt
rm -f combined.txt
Common Mistakes
  1. Using > when you meant >> and accidentally erasing a file's previous contents.
  2. Forgetting that 2> only redirects stderr, so stdout still prints to the screen unless it is redirected too.
  3. Believing < file somehow changes what a command outputs; it only changes where the command reads its input from.
Chapter Summary
  • > truncates and writes; >> appends without erasing existing content.
  • < redirects a file's contents to a command's stdin.
  • 2> redirects stderr only; 2>&1 merges stderr into wherever stdout currently points.
  • &>file (bash-specific) redirects both stdout and stderr to file in one step.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.