Input & Output Redirection (Input & Output Streams) | Linux
2024/01/04
Input & Output Redirection (Input & Output Streams) is a common method used by many programs at runtime to output logs or determine when errors occur. The techniques in this section are essential for daily system administration.
| Name | Syntax | Purpose |
|---|---|---|
| standard out (stdout) | 1> | Typically used to output normal messages |
| standard error (stderr) | 2> | Typically used to output error messages |
| standard in (stdin) | < | Reads data from a file |
Input Redirection (stdin):
This is a standard input redirection symbol. Its function is to write the output of a command to a specified file. Normally, users provide input via the keyboard. For example, when using the cat command to concatenate files, the content is read from the input redirection.
Output Redirection (stdout and stderr):
Output redirection handles data generated by commands. Standard output redirection (stdout) displays regular command output.
Standard Error Stream (stderr):
Used for communicating error messages and alerts. It redirects and controls where error messages are sent.
Examples:
# Redirect stdout to a file
ls -lsah > output.txt
# Redirect both stdout and stderr to a file
ls -lsah > output.txt 2>&1
# If the output is successful, write to ls.txt; if there's an error, write to ls-error.txt (overwrite, replaces original content)
ls -lsah 1> ls.txt 2> ls-error.txt
# If the output is successful, write to ls.txt; if there's an error, write to ls-error.txt (append, does not replace)
ls -lsah 1>> ls.txt 2>> ls-error.txt
# Redirect all output (both success and error) to ls.txt (overwrite, replaces original content)
ls -lsah &> ls.txt
# Redirect all output (both success and error) to ls.txt (append, does not replace)
ls -lsah &>> ls.txt
# If you don't want to save the output, send it to /dev/null — like throwing it into a black hole; the output will not actually be saved
ls -lsah &>> /dev/null