Output Redirection in Linux
Output redirection allows you to control where command output goes, such as sending it to a file instead of the screen.
Standard Output (stdout) Redirection
Redirect output to a file (overwrite)
command > file.txt-
Example
ls > list.txtOverwrites
list.txtwith the output ofls.
Redirect output to a file (append)
command >> file.txt-
Example
echo "Log entry" >> log.txtAppends to
log.txtwithout overwriting existing content.
Standard Error (stderr) Redirection
Redirect errors only
command 2> error.txt-
Example
ls nofile 2> errors.txtStores only the error message in
errors.txt.
Append errors
command 2>> error.txtRedirect Both stdout and stderr
To the same file (overwrite)
command > output.txt 2>&1OR (bash shorthand)
command &> output.txtTo the same file (append)
command >> output.txt 2>&1OR
command &>> output.txtDiscard Output
Discard stdout
command > /dev/nullDiscard stderr
command 2> /dev/nullDiscard both stdout and stderr
command > /dev/null 2>&1Summary Table
| Description | Command |
|---|---|
| Redirect stdout (overwrite) | command > file.txt |
| Redirect stdout (append) | command >> file.txt |
| Redirect stderr | command 2> file.txt |
| Redirect stderr (append) | command 2>> file.txt |
| Redirect both stdout and stderr | command > file.txt 2>&1 |
| Discard all output | command > /dev/null 2>&1 |
Last updated on