Making sense of the copy descriptor operator
Take the example of a user running the command ls >moo 2>&1
or ls 2>&1 1>moo
while he is on his terminal (term). (Note that the 1 is implicit. 1>moo
is identical to >moo
.)
Firstly, understand that x>&y
means: "Make output to x go wherever output to y is going right now."
Knowing that, let's draw a table of what happens at each step of a redirection. Redirections are read from left to right.
ls 2>&1 1>moo
Make output to 2 go wherever output to 1 is going, which is the terminal. Then, make output to 1 go to moo
.
fd | ls | 2>&1 | 1>moo | |------|-------|-------| 1 | term | term | >moo | | \ | | | \ | | | \ | | 2 | term | >term | term |
ls 1>moo 2>&1
Make output to 1 go to moo
. Then make output to 2 go wherever output to 1 is going, which is moo
.
fd | ls | 1>moo | 2>&1 | |------|-------|------| 1 | term | >moo | moo | | | \ | | | \ | | | \ | 2 | term | term | >moo |
Read more
You should also read the more in-depth tutorial about redirection in general: Illustrated Redirection Tutorial.