Output Redirection
Instead of displaying output on screen, send it to a file.
Basic Redirection: >
The > operator sends stdout to a file, creating it if needed.
Overwrite vs Append
> overwrites the file completely!
>> appends to the file.
Careful with >
> destroys existing content. Always think twice before using it on important files. When in doubt, use >>.
Prevent Overwrites: noclobber
Enable noclobber to prevent accidental overwrites:
set -o noclobber # Enable protection
echo "text" > existing.txt # Error: cannot overwrite
echo "text" >| existing.txt # Force overwrite with >|
set +o noclobber # Disable protection
Add set -o noclobber to your .bashrc if you want permanent protection.
Redirect stderr
2> redirects stderr (file descriptor 2).
Redirect Both Streams
To Different Files
To Same File
Discard Output: /dev/null
/dev/null is a black hole. Anything written to it disappears.
Silent Commands
command &> /dev/null is useful when you only care about the exit code, not the output.
Save and Display: tee
What if you want to save output AND see it?
We'll cover tee in detail later.
Real-World Examples
Save Command Output
Append to Log
Capture Errors
Run Silently
A Common Gotcha
This doesn't work as expected:
cat file.txt > file.txt # WRONG - empties the file!
The shell opens file.txt for writing (emptying it) before cat can read it.
Solution: use a temp file or sponge from moreutils.
What's the difference between > and >>?
Quick Reference
| Syntax | Effect |
|---|---|
> file | Redirect stdout, overwrite |
>> file | Redirect stdout, append |
2> file | Redirect stderr |
2>> file | Append stderr |
&> file | Redirect both (overwrite) |
&>> file | Redirect both (append) |
> /dev/null | Discard output |
Key Takeaways
>redirects stdout to file (overwrites)>>appends instead of overwriting2>redirects stderr&>redirects both stdout and stderr/dev/nulldiscards output silently- Be careful with
>- it destroys existing content
Next: input redirection with <.