Overview of Redirection
In Linux systems, all input and output are treated as files. Redirection changes the direction of these standard I/O streams, allowing command output to be written to a file instead of being displayed on the screen, or allowing the content of a file to be used as input for a command.
Standard Input/Output Streams
All commands typically use the following three standard streams:
- Standard Input (stdin, 0): The channel from which a command reads data. The default is the keyboard.
- Standard Output (stdout, 1): The channel where a command's normal output is displayed. The default is the screen (terminal).
- Standard Error (stderr, 2): The channel where a command's error messages are displayed. The default is the screen (terminal).
Redirection Operators
Various redirection operators can be used to control the direction of input/output. Using 'redirect' directly as a command, as shown in the generated commands below, will result in an error. You must use symbols like >, >>, <, etc.
1. Standard Output Redirection
2. Standard Error Redirection
3. Standard Input Redirection
Generated command:
Try combining the commands.
Description:
`redirect` Executes the command.
Combine the above options to virtually execute commands with AI.
Common Examples
Explore various examples utilizing redirection to learn how to control input and output.
Save Command Output to File
ls -l > file_list.txt
Saves the output of the `ls -l` command to `file_list.txt`, overwriting the file if it already exists.
Append Multiple Command Outputs to One File
echo "--- 작업 시작 ---" >> log.txt
date >> log.txt
Appends the output of the `echo` command to `log.txt`, then appends the output of the `date` command to the same file. `>>` is used to preserve existing content.
Separate Error Messages to a Dedicated File
ls non_existent_file 2> error.log
Executes an `ls` command for a non-existent file and redirects only the error messages (`2>`) to `error.log`. Normal output will still appear on the screen.
Pass Input File to Command
sort < numbers.txt
Specifies `numbers.txt` as the input for the `sort` command to sort the file's contents. `sort` processes the file content as standard input.
Redirect Both Output and Error to One File
ls /home non_existent_file &> output_and_error.log
Saves both normal output and error messages to `output_and_error.log`.