How to pipe stderr to a command in Bourne or Korn shell

David Smallberg das at lanai.cs.ucla.edu
Wed Oct 10 05:59:43 AEST 1990


In article <5069:Oct903:10:1390 at kramden.acf.nyu.edu> brnstnd at kramden.acf.nyu.edu (Dan Bernstein) writes:
>In article <1990Oct8.204053.15797 at athena.mit.edu> jik at athena.mit.edu (Jonathan I. Kamens) writes:
>> A similar approach will work in sh (and probably ksh), although there's
>> probably some better way to do it with various hideous file descriptor
>> reassignments.
>...
>  ( exec 5>&1; exec 1>&2; exec 2>&5; foo ) | err-processor

Unnecessary subshell creation.  This works under sh and ksh:
	{ pgm1 2>&1 1>&3 | pgm2 ;} 3>&1
Explanation:
     Suppose stdout originally goes to <stdout> (whether that be a file, the
 terminal, or whatever).
     Outside the { }, we open file descriptor 3 to also go to <stdout>.
     pgm2's stdout is unaffected, so it will go to <stdout>.
     The "|" at first causes pgm1's stdout to go into the pipe.
     The "2>&1" causes pgm1's stderr to also go into the pipe.
     The "1>&3" causes pgm1's stdout to no longer go into the pipe, but into
	file descriptor 3, which goes to <stdout>.
Result:
     pgm1's stderr goes into the pipe.
     pgm1's stdout and pgm2's stdout go to the original stdout destination.
     pgm2's stderr goes to the original stderr destination.
Now only pgm1's stderr
	goes into the pipe.
--

-- David Smallberg, das at cs.ucla.edu, ...!{uunet,ucbvax,rutgers}!cs.ucla.edu!das



More information about the Comp.unix.shell mailing list