In shell scripting, 1 is file descriptor for standard output and 2 is for standard error. Now, since both of these point to console what is the use of
2>&1. Are not they already pointing to the same device?
- 449
- 2
- 7
- 18
-
6http://stackoverflow.com/questions/818255/in-the-shell-what-does-21-mean?rq=1 – Zain Aftab Aug 20 '15 at 07:46
-
1Welcome to Stack Exchange, please have a look at http://stackoverflow.com/help/asking and do proper research in order to do useful questions – Javier Aug 20 '15 at 07:54
1 Answers
The short answer is you are redirecting stderr to stdout so you get both error messages written to FD2 as well as normal output on FD1 written to FD1. (FD = File Descriptor). It generally allows you to capture the output of error messages you want to save in a log file, etc.. that would otherwise not be captured simply by redirecting stdout to the log.
By way of brief background, your shell has 3 well known file descriptors that cover basic reading and writing:
0 - stdin (your input buffer)
1 - stdout (your normal output descriptor)
2 - stderr (your normal error descriptor)
When you read or write, just about any programming language, including your shell, makes use of these common file descriptors to manage the input/output. In your shell, you have the ability to redirect or combine output from stdout and stderr. The general format is:
m > &n ## where n & m are 1, 2
You can combine, for instance, both the stdout and stderr from any command to a file with:
./someprogram > myfile 2>&1
Which basically says, "take the output from someprogram on stdout redirect it to myfile while including stderr in stdout.
There are several good references, one being BASH Programming - Introduction HOW-TO: All about redirection
Note: Be sure you also understand that redirection can happen on a temporary (per command basis) or can be set for the scope of the script using exec.
- 1
- 1
- 81,885
- 6
- 58
- 85