Jeff Abrahamson on 9 Jan 2004 03:31:02 -0000


[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Re: [PLUG] changing stdout in a script


On Thu, Jan 08, 2004 at 12:18:02PM -0500, Geoff Rivell wrote:
>   [32 lines, 180 words, 1131 characters]  Top characters: _teoiasn
> 
> On Wednesday 07 January 2004 06:07 pm, mjd-lists-plug@plover.com wrote:
> > Jeff Abrahamson <jeff@purple.com>:
> > > Can a shell script change where stdout goes?
> > >
> > > I have a shell script that creates a directory.  I would like to have
> > > echo and all other instances of output to stdout go to a file in this
> > > directory.
> > >
> > > Of course, I could do this with two scripts, one of which is a
> > > wrapper.  Does anyone know a way to do this with just one script?
> >
> >         exec >the-file
> >
> > will redirect the standard output.
> >
> > If you will want to put it back the way it was later on, you may
> >
> >         exec 3>&1 >the-file
> >
> > before and
> >
> >         exec 1>&3 3>&-
> >
> > after.
> 
> Can't he just use the command 'script' to do this?  You run that and 
> everything gets logged to a file.  Or am I missing the conversation?

The goal was to avoid having to write a wrapper script.  With two
scripts the problem is trivial:

  foo:

    #!/bin/sh
    foo-sub > out-file 2> err-file


I think Mark's exec solution is elegant and Right(tm).  It has many
nice properties, including, importantly, that future maintainers are
unlikely to miss some bit of scoping and break it.  The nice but
kludgy proposal to use braces and redirect the entire scope they
created had that one single problem.

-- 
 Jeff

 Jeff Abrahamson  <http://www.purple.com/jeff/>
 GPG fingerprint: 1A1A BA95 D082 A558 A276  63C6 16BF 8C4C 0D1D AE4B

Attachment: pgpUSaD09BP9v.pgp
Description: PGP signature