I cannot understand the difference between these two cases:
./a.out > outfile 2>&
I can see both standard output and error output in outfile
./a.out 2>& > outfile
I can only see standard output int outfile, and error output was printed on the screen
How should I understand this? I think they are the same!
n> file
creates/truncates file
and associates it to file descriptor n
. If n
is not specified, 1
(i.e. standard output) is assumed.
n>&m
copies (using dup2()
) file descriptor m
onto n
.
So if you write ./a.out 2>& >outfile
, then the standard output descriptor is first copied onto the stderr descriptor, and then stdout is redirected to outfile.
You can see those redirection operators as assignments if you like:
2>& >file
would be read as fd2 := fd1; fd1 := "file"
, which is not the same as>file 2>&
which is fd1 := "file"; fd2 := fd1
Redirections are applied in order. In 2>&1 > file
, first stderr
is replaced with a copy of stdout
, then stdou
t is replaced with a newly opened file. Think of each redirection as a dup2
call in C.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With