Wandering Thoughts archives

2009-07-02

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 ...

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).

unix/GettingPipelineStatus written at 00:28:50; Add Comment


Page tools: See As Normal.
Search:
Login: Password:
Atom Syndication: Recent Pages, Recent Comments.

This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.