Capturing Exit Status in Pipelines

Dear Lazyweb,

Okay, here’s my problem. I’ve got to capture the exit status of a command partway through a shell pipeline.

The obvious way of doing this would be something like (if I wanted to capture the exit status of bar):

foo | { bar ; result=$? } | baz

But it looks like the bracketed subexpression ends up getting executed in a different subshell in this case, so the new value of $result never makes it back to the parent shell. Also the korn/bourne shells on some propreitary OSes don’t seem to parse this construct correctly.

Any other solutions?

Update: Jesse writes:

It depends on what you need to do with the output of baz, but one thing that will work is:

(foo | ( bar 3>&-; echo $? >&3 ) | baz) 3>&1

Variations will let you do pretty much whatever you like. For example, to save the result of bar in $result but still have the output of baz go to stdout:

result=`(foo | ( bar 3>&-; echo $? >&3 ) | baz >&4 ) 3>&1` 4>&1
hoodwink.d enhanced