![Redirect stderr to stdout in Bash](https://tecnstuff.net/wp-content/uploads/2020/10/bash-redirect-stderr-stdout.jpg)
Sometimes when you are redirecting the output of a command by piping to another command or to a file, you get the error messages. There are three standard I/O streams, which are used in Bash and other Linux shells when a program is executed.
Below are the streams and each representing by the numberic file descriptor:
0
–stdin
, it’s standard input stream.1
–stdout
, the standard output stream.2
–stderr
, standard error stream.
Here,
- The input stream gives the information to the program, commonly by typing in the keyboard.
- Output of the program goes to the standard output stream.
- The error messages goes to the standard error stream.
Redirecting Output
Using the redirection you can easily get the output from a program to another program or a file as input.
To redirect streams you should use the n>
operator, where n
is the file descriptor number.
If you will not provide the value of n
, by default it will set to 1
. Let’s see example for the better understanding. Below given two commands are same. Both commands will redirect the command output to a file.
command > file
command 1> file
Let’s say you want to save output of the date command to a file, use below command:
date > today.txt
Use the cat command to view contain of today.txt
file:
cat today.txt
Sun Dec 13 04:47:45 UTC 2020
To redirect the standard error (stderr
) use the 2>
operator:
command 2> file
To redirect the both standard error (stderr
) and output (stdout
) to two separate files using below command:
command 2> error.txt 1> output.txt
If you don’t want to show error messages on the screen, redirect stderr
to /dev/null
:
command 2> /dev/null
Redirecting stderr to stdout
When you want everything of program’s output in a single file, redirect the stderr
to stdout
.
Use the following command to redirect the stderr
to stdout
and error messages sent to the same file as standard output:
command > file 2>&1
Here, > file
redirect the stdout
to file, and 2>&1
redirect the stderr
to the current location of stdout
.
Ensure the order of redirection, it’s important. For instance, in the below example it redirects only stdout
to file. Here the stderr is redirected to stdout
before the stdout
was redirected to file.
command 2>&1 > file
You can use the &>
construct instead of 2>&1
, both have the same meaning in Bash.
command &> file
Conclusion
I hope you learned the concept of the redirections and file descriptors. To redirect stderr and stdout, use the 2>&1
or &>
constructs. Learn more visit the bash man page
If you have any questions or feedback, feel free to leave a comment.