Order 2> & 1 when redirecting std error to file
I see several different formats for redirecting std output to a file:
a. command 1&2>output.txt
b. command >output.txt 2>&1
c. command 2>&1>output.txt
d. command &>output.txt
Is there a difference between them? If 2>&1
placed at the end (b), how does it redirect the stderr of the first command?
source to share
Yes. The order matters. >
can recreate the idea of pointing and pointers / links and the word "redirection", but fd redirection is more like assignments. That is, if you do
exec 2>&1 1>output.txt
It will "assign" the "current" value "(the actual file opened with that file descriptor) of the file descriptor 1
to the file descriptor 2
, and then open output.txt
and assign it to the file descriptor 1
.
What it won't do is the point &2
(read and as a "file descriptor") before &1
. It will not ask for a &2
request &1
. A file descriptor is only associated with the actual file, never with another file descriptor. 2>&1
links a file opened &1
with &2
. It does not redirect &2
in &1
the sense that writing in &2
will cause it to write to which one it &1
is currently connected to. &1
can later be reopened with another file that it was linked to during the redirect 2>&1
, but this will not affect what is written &2
.
Check out dup2 (2) if you want to know how this function is displayed at the system call level.
source to share