Peek at Pipes by Copying Stdout to Stderr

I’m stringing commands together and want to see what’s passing through a particular point. Technically tee (Linux/UnixUtils) can do this. Its sole purpose is to duplicate stdout to a file, like a metaphorical “T” connector.

echo hello | tee somefile.txt | sed "s/e/a/"

 
Attentive readers will be thinking,
“The post just started; what’s wrong with it?” :P
 
*clickety-click*… Nothing, this works:

echo hello | tee /dev/stderr | sed "s/e/a/"

 
*drumroll*… on Linux, where everything’s a file.

While many MinGW ports on Windows internally translate the likes of “/dev/stderr”, the UnixUtils tee does not. A hyphen arg obediently makes a file named “-”. Linux guys can keep reading; this trick is nifty.
 

Objective: Put a command in the pipeline that reads from stdin, and relays to both stdout and stderr.

echo hello | gawk "{print; print > \"/dev/stderr\";}" | sed "s/e/a/"

Printing without an arg defaults to $0, incoming lines.
Meh. The gawk part could be tucked into a batch script, but there’s a shorter way.
 
 

echo hello | sed -u "w /dev/stderr" | sed "s/e/a/"

There’s a lot more to sed than subtitution.* It can write files too. And by default, it already echoes to stdout. The optional -u makes it buffer less to keep the stream flowing.
 
 
* When you’ve soaked up that sed guide, this cheat sheet will make sense.

Tags: , ,

Leave a Reply