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:
stdin, it’s standard input stream.
stdout, the standard output stream.
stderr, standard error stream.
- 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.
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
Sun Dec 13 04:47:45 UTC 2020
To redirect the standard error (
stderr) use the
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
command 2> /dev/null
Redirecting stderr to stdout
When you want everything of program’s output in a single file, redirect the
Use the following command to redirect the
stdout and error messages sent to the same file as standard output:
command > file 2>&1
> file redirect the
stdout to file, and
2>&1 redirect the
stderr to the current location of
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
I hope you learned the concept of the redirections and file descriptors. To redirect stderr and stdout, use the
&> constructs. Learn more visit the bash man page
If you have any questions or feedback, feel free to leave a comment.
Leave a Reply