Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does descriptor redirection seem inconsistent?

Tags:

bash

  • Most of us know that to redirect STDERR to STDOUT we do 2>&1
  • We also know about FILE redirection using ">" and process redirection using "|"

What I always wondered about was about the combination of the above two

If you want to redirect both STDERR and STDOUT of prog1 to prog2 you place the 2>&1 prior to the |prog2 pipe. On the other hand, if you are redirecting STDERR and STDOUT of prog1 to a file (file.txt), the 2>&1 goes after the > file.txt.

So I know HOW to do it, I am just wondering WHY it is done like that. To me it seems inconsistent, but I may be looking at it the wrong way

Thanks

like image 625
nhed Avatar asked Dec 05 '25 14:12

nhed


2 Answers

They are processed in order.

So if you do

progname 2>&1 1>out.txt

That diverts stderr from the program to the current destination of the program's stdout, which is the stdout stream of the shell, and diverts stdout of the program to out.txt.

if you do

progname 1>out.txt 2>&1 

That diverts the stdout of the program to out.txt, then diverts the stderr from the program to the current destination of the program's stdout, which is out.txt.

like image 154
Ben Avatar answered Dec 07 '25 07:12

Ben


It helps if you don't think of a pipe as redirection. Using 2>&1, you're redirecting stderr to stdout. Only stdout goes through a pipe. If you redirect stdout before a pipe, then nothing goes through.

like image 21
Dennis Williamson Avatar answered Dec 07 '25 07:12

Dennis Williamson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!