On Thu, 14 Jan 2010 11:54:01 +0000
Colin Watson <[email protected]> wrote:

> >     # show what five file utils output to STDIN only
> 
> You mean stdout, not stdin.  Outputting to stdin would be even
> weirder. :-)

That would be strange...  guess my mind was inputing from STDERR.
Thanks for the facts & fast fix.



PS:

(Or "Trivia Section", weirder but maybe practical, for shell
scripting buffs, as suggested by the occasion.)

After some thinking & fussing I learn STDIN can be used like a prefab
short-term named pipe.  

        # an 'ls' that outputs to STDERR and STDOUT
        % ls nosuchfile /bin/bash
        ls: cannot access nosuchfile: No such file or directory
        /bin/bash

        # run 'wc' on both separately, with no extra files or named pipes
        % { { { ls nosuchfile /bin/bash  >& 0 ; } 2>&1 | wc -c 1>&2 ; } 0>&1 | 
wc -c ; } 2>&1
        56
        10

How that works.  Send STDOUT to STDIN, making STDIN a temporary
buffer.  Then send STDERR to STDIN, pipe that to 'wc', which counts
it, and sends the count to STDERR, making STDERR another temporary
buffer.  Then send STDIN back to STDOUT, and pipe that to 'wc' too.
Result: separate character counts.

Abstracted to a shell function:

        # and while we're at it, why not allow for a third argument
        # Usage: twice "input command" [ "command for STDERR" ] [ "command for 
STDIN" ]
        % twice() { [ "$1" ] || exit 1 ; C1="${2:-cat}" ; C2="${3:-$C1}" ; { { 
{ $1 >& 0 ; } 2>&1 | $C1 1>&2 ; } 0>&1 | $C2 ; } 2>&1 ; }
        % twice "ls nosuchfile /bin/bash" "wc -c"
        56
        10
        # with 3 args, the 3rd a second command
        % twice "ls nosuchfile /bin/bash" "rev" "dog --rot=2"
        yrotcerid ro elif hcus oN :elifhcuson ssecca tonnac :sl
        /dkp/dcuj

'twice' resembles the 'pee' command in the 'moretutils' package, except
'pee' doesn't know from STDERR.  

I've been wondering for ages how to efficiently and conveniently
process STDOUT & STDERR separately, or if it was possible.  Thanks for
the acorn, CW.



-- 
To UNSUBSCRIBE, email to [email protected]
with a subject of "unsubscribe". Trouble? Contact [email protected]

Reply via email to