Redirection is a fundamental Linux concept that allows you to control where command input comes from and where output goes. Instead of displaying results on screen, you can send them to files, other commands, or devices. This is crucial for automation, logging, and data processing.
Key Concepts
- stdin (0): Standard input stream (keyboard)
- stdout (1): Standard output stream (screen)
- stderr (2): Standard error stream (screen)
- File Descriptors: Numeric identifiers for streams
- Pipes: Connect output of one command to input of another
Command Syntax
command > file - Redirect stdout to file
command < file - Redirect stdin from file
command >> file - Append stdout to file
command 2> file - Redirect stderr to file
Common Options
> - Redirect stdout (overwrite)
>> - Redirect stdout (append)
< - Redirect stdin
2> - Redirect stderr
&> - Redirect both stdout and stderr
| - Pipe output to another command
Practical Examples
Example 1: Basic Output Redirection
|
|
Saves directory listing to file instead of screen
Example 2: Append to File
|
|
Adds content without overwriting existing data
Example 3: Error Redirection
|
|
Sends permission errors to file, shows results on screen
Example 4: Redirect Both Streams
|
|
Captures both normal output and errors
Example 5: Input Redirection
|
|
Reads input from file instead of keyboard
Example 6: Here Documents
|
|
Creates multi-line input without external file
Use Cases
- Logging: Save command output for later review
- Automation: Scripts that process files silently
- Data Processing: Chain commands together with pipes
- Error Handling: Separate errors from normal output
- Batch Operations: Process multiple files efficiently
Related Commands
tee - Write output to both file and stdout
cat - Display file contents or concatenate
sort - Sort lines of text
grep - Search text patterns
wc - Count lines, words, characters
Tips & Troubleshooting
Common Issues
- File Overwrite: Use
>>to append, not> - Permission Denied: Check write permissions on target
- Mixed Output: Redirect stderr separately if needed
Best Practices
- Always redirect errors in scripts:
2>/dev/null - Use absolute paths in automated scripts
- Test redirections with small datasets first
- Combine with
teeto see output AND save it
Advanced Techniques
|
|
Security Notes
- Be careful with
>- it overwrites without warning - Redirect sensitive output to protected directories
- Use proper file permissions on log files