Finding out when a command in a pipeline fails

July 2, 2009

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 FAQ, but if I had to do this I would just use a flag file:

(may-fail || touch $FAILFILE) | grep ...

If $FAILFILE exists after the pipeline has finished, may-fail failed.

If you need to distinguish between commands 'failing' due to SIGPIPE 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).

Written on 02 July 2009.
« A Unix irritation: pipeline status
How software makes reverse proxying hard »

Page tools: View Source, Add Comment.
Login: Password:
Atom Syndication: Recent Comments.

Last modified: Thu Jul 2 00:28:50 2009
This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.