File Redirection Basics
What is File Redirection?
File redirection is a powerful feature in Linux that allows you to change the standard input, output, and error streams of a command. It enables you to send the output of a command to a file, read input from a file, or redirect error messages.
Standard Streams in Linux
Linux uses three standard streams for input and output:
Stream |
Description |
File Descriptor |
stdin |
Standard Input |
0 |
stdout |
Standard Output |
1 |
stderr |
Standard Error |
2 |
Basic Redirection Operators
graph LR
A[Command] --> B{Redirection Operator}
B -->|>| C[Output to File]
B -->|>>| D[Append to File]
B -->|<| E[Input from File]
B -->|2>| F[Error to File]
Output Redirection (>
)
The >
operator redirects the standard output of a command to a file, overwriting the file's existing content.
Example:
ls > file_list.txt
Append Redirection (>>
)
The >>
operator appends the output to the end of an existing file.
Example:
echo "New log entry" >> system.log
The <
operator reads input from a file instead of keyboard input.
Example:
sort < unsorted.txt
Error Redirection (2>
)
The 2>
operator redirects error messages to a file.
Example:
find / -name "example" 2> errors.log
Why Use File Redirection?
File redirection is essential for:
- Logging command outputs
- Processing large amounts of data
- Automating system tasks
- Debugging and error tracking
By mastering file redirection, you can significantly enhance your Linux command-line productivity. LabEx provides comprehensive Linux environment for practicing these techniques.