2>&1
What does this mean? This command used to confuse me at times. So I will explain about it in this blog.
Well there are 3 standard input and output streams:
0 - Standard input
1 - Standard output
2 - Standard error
"X>&Y" => copy the file descriptor Y to X.
Point to note: this is copy by value (remember this and you will not get confused between commands).
Example 1:
$ some-command > file 2>&1
The above command will redirect both Standard output and error to file.
How?
- > file implies that redirect standard output to file
- 2>&1 implies copy the file descriptor of 1 to 2, hence 2 gets redirected to the file as well
$ some-command 2>&1 >file
The above command will redirect standard output to file but standard error will still be displayed on the console.
Why?
- 2>&1 copies file descriptor of 1 to 2 which would mean to display on console
- > file implies redirect standard output to file. Hence the standard error on the console.
standard error, output to a file and to console as well
Simply do:
$ some-command 2>&1 | tee file
How?
- 2>&1 copy fd of 1 to 2.
- A pipe(|) simply directs standard output from the first command to the standard input of the second command.
- tee basically copies standard input to standard output.
Example 4:
If you don't want to see the output of standard error at all. Then simple do the following:
$ some-command 2>&-
Simple enough!!!
Enjoy.
Thanks for awesome post!!
ReplyDelete