I found this line at the end of each script in crontab. I was amazed to find what’s the importance and use of 2>&1.

If you are familiar with UNIX I/O redirection, syntax similar to the following should not be new to you:

command > file 2>&1

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?

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,

command > file 2>&1

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.