Finding out when a command in a pipeline fails
Suppose you are in the situation from last entry and
want to know whether
may-fail actually failed, and you don't want to
just split the pipeline up and use a temporary file.
In Bash, a commentator on the last entry pointed out that this is
simple: you can use the
$PIPESTATUS array variable to see the output
status of any command in the pipeline. The same feature is available in
zsh, but it uses
$pipestatus (lower case), just to be different.
If you want to do this in general Bourne shell, you need some way to communicate the exit status of the command out of pipeline. You could use the very complicated mechanisms from the old comp.unix.shell FAQ, but if I had to do this I would just use a flag file:
rm -f $FAILFILE
(may-fail || touch $FAILFILE) | grep ...
$FAILFILE exists after the pipeline has finished,
If you need to distinguish between commands 'failing' due to
and other failures, your life is much more complicated. Fortunately I
have never had to do that (or unfortunately, since it means that I have
no code to share).
Some people would say that splitting a pipeline up and using temporary files is less elegant and thus less desirable than any of these techniques. I disagree; Bourne shell programming is already too complicated, so you should avoid tricky techniques unless they're absolutely necessary. Using a temporary file is almost never going to kill you and it makes your script easier to follow (especially if you add comments).