How to redirect stderr and stdout to a file
Managing output is a common task in Linux. Commands often redirect errors and output to files so they can be stored and inspected later. This is particularly useful for commands or programs that produce too much output to read as it appears. Redirecting it to a file lets us read the complete details afterward. This article covers managing output and errors while a command runs.
The Linux Bash shell has three types of input and output:
- stdin (standard input) receives input for a program, such as keyboard input.
- stdout (standard output) sends output to the screen.
- stderr (standard error) sends error output to the screen.
These three types can be represented by the following numbers:
- 0 = stdin (standard input)
- 1 = stdout (standard output)
- 2 = stderr (standard error)
* To redirect both stdout and stderr, use ”&”. This operator is available from Bash 4 onward. Examples:
-
Redirect error messages to error.log while running a program or command:
[tum@Ezylinux ~]$ program-name 2> error.log [tum@Ezylinux ~]$ command 2> error.log -
Redirect stderr to stdout:
[tum@Ezylinux ~]$ command 2>&1 -
Redirect error messages to error.log and output to output.log while running a program or command:
[tum@Ezylinux ~]$ program-name 1>out.log 2>err.log -
Redirect error messages and output to out.log while running a program or command:
[tum@Ezylinux ~]$ command &> out.logOr:
[tum@Ezylinux ~]$ command 2>&1 >out.log