stdout/stderr redirection

You must know the standout redirection:

ls > file

The output of ls is now saved in file “file”. This is equivalent to:

ls 1>file

Note that there is no space between 1 and >. 1 is the file descriptor of standard output.  1>file means file descriptor 1 (standard output) is now redirected to file “file”. Whether there is space between > and file does not matter.

ls 2>file means redirecting file descriptor 2(standerr) to file “file”. Also, there is no space between 2 and >, and the space between > and file does not matter.

ls 2>&1 means redirecting file descriptor 2 (standard error) to file descriptor 1(standard output). So “ls 1 > 2 2&1″ will create a file 2 and output “ls: cannot access 1: No such file or directory”(standard error) in that file if file 1 does not exist. Note that &1 means file descriptor 1(standard output). If you write “ls 2>1″, that means stand err is redirected to file “1″, not file descriptor 1. So you will find an empty file 1 in current directory.

Considering there are two files:file1,file2 in current directory. What about the result of “ls > 2″. Does the file 2 contain the following lines?



Actually, the content of file 2 is




This example tells us that shell creates the file to redirect to, before it executes the command.

Now considering there are only two files:file1 and file2 in current directory, what about the result of “ls 2 2>&1 > 1″?

The command will generate a message “ls: cannot access 2: No such file or directory” on the screen, and file “1″ is an empty file. We know the message is a standard error, but why it is not redirected to file “1″? Well, that is because before standard output is redirected to file “1″, the standard error is redirected to the old standard output(the screen). To redirect stand err to file “1″, you should write “ls 2 > 1 2>&1″. From this example, we can know how important the order of redirection is!





Posted in tips of hosting