简体   繁体   中英

How should I understand “> outfile 2>&1” and “ 2>&1 > outfile”?

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!

n> file creates/truncates file and associates it to file descriptor n . If n is not specified, 1 (ie 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" fd2 := fd1; fd1 := "file" , which is not the same as
  • >file 2>& which is fd1 := "file"; fd2 := fd1 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.

According to the Bash Reference Manual , “2>&1 > file” directs only the standard output to “file”, because the standard error output was made a copy of the standard output; while “> file 2>&1” directs both the standard output and the standard error output to “file”.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM