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.txt
Overwrites
list.txt
with the output ofls
.
Redirect output to a file (append)
command >> file.txt
-
Example
echo "Log entry" >> log.txt
Appends to
log.txt
without overwriting existing content.
Standard Error (stderr
) Redirection
Redirect errors only
command 2> error.txt
-
Example
ls nofile 2> errors.txt
Stores only the error message in
errors.txt
.
Append errors
command 2>> error.txt
Redirect Both stdout
and stderr
To the same file (overwrite)
command > output.txt 2>&1
OR (bash shorthand)
command &> output.txt
To the same file (append)
command >> output.txt 2>&1
OR
command &>> output.txt
Discard Output
Discard stdout
command > /dev/null
Discard stderr
command 2> /dev/null
Discard both stdout and stderr
command > /dev/null 2>&1
Summary 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