I have come to understand that we have two methods of redirecting both stdout and stderr to the same file. The first method is:
ls -l /bin > ls-output.txt 2>&1
As the author of this book states: Using this method, we perform 2 redirections, first we redirect stdout to ls-output.txt and then we redirect stderr(file descriptor 2) to stdout(using file descriptor 1).
The order of redirections is important.
ls -l /bin 2>&1 >ls-output.txt
would redirect stderr to screen.
My question is: Like in many programming languages, was the command designed with some associativity and precedence rules in mind and how do we read the command while writing it on screen? and what is the sequence of the backend execution of the command?
Here's what i think about the execution sequence:
First, the command ls -l /bin
sends its output to stdout and error to stderr(any one of those).
Then, the stderr is redirected to stdout.(if there is any error, eg: if ls -l /binn
is used)
Now, the stdout stream contains one of the two(either output or error) which it then redirects to the file ls-output.txt
ls
ever starts. It's handled by the shell. See, for example, the Bash Hackers Wiki, or the links in this SO question. – muru Jan 05 '15 at 12:47