Linux redirecting both stout and stderr to a file

Posted on

Problem :

Given that “files.txt” is a file in my working directory and “not-here” is not, my question is regarding this statement:

ls files.txt not-here >out 2>&1

Why does this combine stdout and stderr before redirecting the combined result to out? Working out the logic sequentially from left to right, it seems to me that the contents of stderr isn’t redirected to stdout until after stdout has already been redirected to out. Doing

ls files.txt not-here 2>&1 >out

seems like it would make more sense to redirect both streams to out since you’re combining the contents of stdout and stderr into stdout, THEN redirecting stdout to out, but this only redirects stdout. It seems the sequence in which things happen here is not what I think it is.

Solution :

The >& operator is a copy operator. 2>&1 means, make file descriptor 2 a copy of file descriptor 1.

If you do 2>&1 >out, when 2>&1 gets executed, fd 1 is still the terminal, fd 2 becomes a copy of fd1, so fd 2 becomes the terminal. Then >out gets executed, fd 1 becomes the file out.

From Bash Mannual :

ls 2>&1 > dirlist
directs only the standard output to file dirlist, because the standard error was made a copy of the standard output before the standard output was redirected to dirlist.

Leave a Reply

Your email address will not be published. Required fields are marked *