bug-bash
[Top][All Lists]
Advanced

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

Re: ...Limitation?


From: Stephane Chazelas
Subject: Re: ...Limitation?
Date: Tue, 26 Sep 2006 18:46:39 +0100
User-agent: Mutt/1.5.6i

On Tue, Sep 26, 2006 at 11:45:42AM -0400, Paul Jarc wrote:
> mwoehlke <address@hidden> wrote:
> > I am trying to figure out how to run a command and pipe the output 
> > through tee, and then check the status of the original command.
> 
> This uses a bash-specific feature:
> cmd > >(tee file); status=$?

This is a ksh feature that can also be found in zsh.

But it's true it's not standard. I may be wrong but I don't
think bash has any significant feature of its own.

What is bash specific is the $PIPESTATUS array. zsh also has it
but it's called $pipestatus there as zsh arrays are
traditionally lowercase (so that they are not confused with
scalar variables (all bash variables are both array and
scalar at the same time as in ksh)).

cmd | tee file

and cmd exit status can be found in ${PIPESTATUS[0]}.


> This should work on any sh:
> exec 3>&1 && status=`exec 4>&1 && { cmd; echo $? >&4; } | tee file >&3`

You may want to write it:

exec 3>&1 && status=`exec 4>&1 && { cmd 4>&-; echo $? >&4; } | tee file >&3`

because otherwise, if cmd spawns a process, and that process
doesn't close its fd 4, you'd have to wait for it to finish (you
may have the same problem if it doesn't close its fd 1 because
of the pipe to tee, though).

> Or, if you don't want to clobber any descriptors, in case they might
> be in use for something else:
[...]

Then do it in a subshell (unless cmd makes use of those file
descriptors) or do it this way instead of using exec (bash will
take care of restoring the fds):

{
  status=$(
    {
      {
        cmd 4>&-
        echo "$?" >&4
      } 3>&- |
        tee file >&3 3>&-
    } 4>&1
  )
} 3>&1

This should work in any Unix or POSIX conformant sh, not in the
Bourne shell.

-- 
St├ęphane




reply via email to

[Prev in Thread] Current Thread [Next in Thread]