Re: How to inherent non-zero exit status using pipe? (dash)

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


On 08/11/2010 06:34 AM, Peng Yu wrote:
> Hi,
> 
> The following example returns the exit status of the last command in a
> pipe. I'm wondering if there is a way to inherent non-zero exit status
> using pipe. That is, if there is any command in a pipe that return a
> non-zero status, I'd like the whole pipe return a non-zero status.

Generally not possible using only POSIX constructs (bash's 'set -o
pipefail' and '${PIPESTATUS[@]}' are extensions).  But what you _can_ do
is play with exec to be able to propagate non-zero status from a
particular portion of a pipeline through a temporary variable or file:

$ exec 3>&1 # duplicate original stdout
$ result=$(
  exec 4>&1 >&3 3>&- # move cmd subst stdout, and restore original
  { ./main.sh; echo $? >&4 # run command, and record its status
  } | head -n 3)
$ echo $? # status from head
$ echo $result # status from ./main.sh
$ exec 3>&-

-- 
Eric Blake   eblake@xxxxxxxxxx    +1-801-349-2682
Libvirt virtualization library http://libvirt.org

Attachment: signature.asc
Description: OpenPGP digital signature


[LARTC]     [Bugtraq]     [Yosemite Forum]     [Photo]

Powered by Linux