The Standard UNIX File Descriptors - Standard Input (stdin), Standard Output (stdout), and Standard Error (stderr)
If you are familiar with UNIX I/O redirection, syntax similar to the following should not be new to you:
Briefly, when command runs it sends "normal" output to file, and any error messages generated by command are also written to file. "2>&1" handles the latter.
Have you ever wondered where the numbers 2 and 1 come from? This may be common knowledge to our more experienced readers, buy may need some explaining to those who are relatively new to the UNIX operating system environment. The 2 and 1 are file descriptors. Okay, so what's a file descriptor?
When a UNIX program wants to use a file, it must first open that file. When it does so, UNIX will associate a number with the file. This number, which is used by the program when reading from and writing to the file, is the file descriptor.
A typical UNIX program will open three files when it starts. These files are:
- standard input (also known as stdin)
- standard output (also known as stdout)
- standard error (also known as stderr)
Standard input has a file descriptor of 0, standard output uses 1, and the number 2 is used by standard error. Are you starting to see where this is headed?
Looking at our command again,
you should now recognize that 2>&1 instructs the shell to send messages headed to stderr (2) to the same place messages to stdout (1) are sent. In our example, that place is file.
If you are wondering, > is equivalent to 1>, and < is short for <0.