Redirection: > >> <

Redirection sends a command's output into a file, or feeds a file into a command's input.

Syntaxcommand > file # overwrite command >> file # append command < file # read from file

By default a command reads from the keyboard and writes to the screen. Redirection changes where that input and output go.

The operators

OperatorMeaning
>Write output to a file, overwriting it.
>>Write output to a file, appending to the end.
<Read input from a file.
2>Redirect error messages (stderr).

Standard streams

Every program has three streams: stdin (input), stdout (normal output) and stderr (error output). Redirection lets you point each one wherever you like.

Example

Example Β· bash
# Save output to a file (overwrites)
echo "First line" > log.txt

# Add another line (appends)
echo "Second line" >> log.txt

# Send errors to a separate file
ls /missing 2> errors.txt

# Send both output and errors to the same file
mycommand > out.txt 2>&1

When to use it

  • A backup script redirects 'rsync' stdout to a log file and stderr to a separate error file for clean post-run analysis.
  • A developer discards verbose tool output with '2>/dev/null' to keep CI logs uncluttered.
  • A sysadmin uses 'tee' to write command output simultaneously to a file and to the terminal for real-time monitoring.

More examples

Redirect stdout and stderr

Shows the three redirection operators: > for stdout, 2> for stderr, and &> for both combined.

Example Β· bash
# Redirect stdout to a file
ls /var/log > filelist.txt

# Redirect stderr to a file
ls /nonexistent 2> errors.txt

# Redirect both to same file
ls /var/log /nonexistent &> all_output.txt

Append and discard output

Demonstrates >> for appending, and /dev/null as a discard target for unwanted output.

Example Β· bash
# Append stdout without overwriting
echo "$(date): job done" >> deploy.log

# Silence stderr completely
find / -name '*.conf' 2>/dev/null

# Silence all output
command > /dev/null 2>&1

Use tee to split output

Uses tee to fan output to both a file and stdout, useful when you need a record and live monitoring.

Example Β· bash
# Write to file AND display on screen
df -h | tee disk_report.txt

# Append to existing log while still displaying
curl -s https://api.example.com/health | tee -a health.log

Discussion

  • Be the first to comment on this lesson.