Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I understand "> outfile 2>&1" and " 2>&1 > outfile"?

Tags:

c

linux

shell

unix

I cannot understand the difference between these two cases:

  1. ./a.out > outfile 2>&

    I can see both standard output and error output in outfile

  2. ./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!

like image 213
Jason Young Avatar asked Dec 25 '22 05:12

Jason Young


2 Answers

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
like image 169
adl Avatar answered Jan 10 '23 18:01

adl


Redirections are applied in order. In 2>&1 > file, first stderr is replaced with a copy of stdout, then stdout is replaced with a newly opened file. Think of each redirection as a dup2 call in C.

like image 45
R.. GitHub STOP HELPING ICE Avatar answered Jan 10 '23 18:01

R.. GitHub STOP HELPING ICE