Output Redirection
Output redirection lets you send command output to files instead of the screen. It's a fundamental concept for automating tasks and saving results.
Standard Streams
Linux has three standard streams:
| Stream | Number | Description |
|---|---|---|
| stdin | 0 | Standard input (keyboard) |
| stdout | 1 | Standard output (screen) |
| stderr | 2 | Standard error (screen) |
Basic Redirection: >
Send output to a file (overwrites):
echo "Hello" > greeting.txt
ls > files.txt
Append: >>
Add to a file (doesn't overwrite):
echo "Line 1" > file.txt
echo "Line 2" >> file.txt
Exercise: Create a File with Redirection
Create a file using echo and redirection:
Redirecting stderr
Errors go to stderr (stream 2):
ls nonexistent 2> errors.txt # Redirect errors only
ls * 2> /dev/null # Discard errors
Redirect Both stdout and stderr
command > output.txt 2>&1 # Both to same file
command &> output.txt # Shorthand (bash)
command > out.txt 2> err.txt # Separate files
The Null Device
/dev/null discards output:
command > /dev/null # Discard output
command 2> /dev/null # Discard errors
command &> /dev/null # Discard everything
Input Redirection
Read input from a file:
sort < unsorted.txt
wc -l < file.txt
Here Documents
Provide multi-line input:
cat << EOF > config.txt
server=localhost
port=3000
debug=true
EOF
Common Patterns
Save Command Output
date > timestamp.txt
ps aux > processes.txt
Create Quick Notes
echo "Remember to commit" >> TODO.txt
Log Output
./script.sh > script.log 2>&1
Discard Unwanted Output
find / -name "file" 2> /dev/null
Overwrite vs Append
| Operator | Effect |
|---|---|
> | Create/overwrite file |
>> | Create/append to file |
echo "First" > file.txt # File contains: First
echo "Second" > file.txt # File contains: Second (overwritten)
echo "Third" >> file.txt # File contains: Second\nThird
Exercise: Append to File
Append a new line to an existing file:
Key Takeaways
>redirects output to a file (overwrites)>>appends to a file2>redirects errors&>redirects both output and errors/dev/nulldiscards unwanted output

