Why does descriptor redirection seem inconsistent?

  • Most of us know that to redirect STDERR to STDOUT we do 2>&1
  • We also know about redirecting FILE with " >" and redirecting processes with " |"

What I was always interested in was the combination of the two

If you want to redirect STANDR and STDOUT from prog1 to prog2 , you put 2>&1before the tag |prog2. On the other hand, if you redirect STDERR and STDOUT prog1 to a file (file.txt), 2>&1comes after > file.txt.

So, I know HOW to do this, I’m just wondering WHY this is done so. This seems inconsistent to me, but I may not look at it correctly.

thank

+3
source share
2 answers

They are processed in order.

So if you do

progname 2>&1 1>out.txt

This transfers stderr from the program to the current destination of the stdout program, which is the shell stdout stream and redirects the program output to out.txt.

if you do

progname 1>out.txt 2>&1 

This translates the stdout of the program into out.txt, then transfers stderr from the program to the current destination of the stdout program, which is out.txt.

+5
source

This helps if you are not thinking about pipe redirection. Using 2>&1, you redirect stderr to stdout. Only the pipe passes through the pipe. If you redirect stdout in front of a pipe, then nothing happens.

+1
source

All Articles