How redirections work through pipe?

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
lockedscope
Posts: 31
Joined: 12 Jun 2020 10:38

How redirections work through pipe?

#1 Post by lockedscope » 18 Jul 2020 03:31

Handle2 writes to console because stderr is connected to stdout by default. Is this right? :?:

And piped commands could only read from stdin which comes from the stdout of the piping command. So, stderr is not connected to stdout when piping. Is this right? :?:

Code: Select all

(
   echo Output1
   echo Output2 >&2
   
) 
echo --- With piping

(
   echo Output1
   echo Output2 >&2
   
)  | (echo # Running findstr & findstr /A:4E /N "^") 

### Result
Output1
Output2
--- With piping
Output2
# Running findstr
1:Output1

aGerman
Expert
Posts: 4654
Joined: 22 Jan 2010 18:01
Location: Germany

Re: How redirections work through pipe?

#2 Post by aGerman » 18 Jul 2020 05:09

STDin references CONin by default, both STDout and STDerr reference CONout by default. You might imagine the console was a file. You can read it and you can write it. Only these two operations.
Redirections and pipes can only use one STD handle at a time. While you are able to specify the file descriptor (0, 1, 2, ...) for the implementation of redirections, pipes use always stdout on one end and stdin on the other end. That means you have to merge stderr into stdout if you want to process stderr in a pipe. Technically a pipe could also be connected to stderr directly but this feature isn't implemented in the CMD. I'm afraid to understand the details you would have to dig in the Windows API.

Steffen

Post Reply