Unix programs should avoid exiting non-zero for clever reasons

July 8, 2010

Dan Astoorian's comment on yesterday's entry reminded me of this general issue, which I will phrase this way:

Dear authors of Unix programs, please don't invent clever reasons to have your programs exit with a non-zero status.

Unless you have a really good reason, your program should only ever exit non-zero if it has actually failed. Trust me; shell programmers are perfectly competent to check for some property of your output ourselves if we really want to know.

(Even if you think you have a really good reason and a really important non-error thing to communicate with your non-zero exit status, you will make shell programmers very happy if you provide a command line switch to turn this behavior off so that you really truly only exit non-zero for real errors. The only exception if pretty much all possible uses of your program will have to examine your exit code to determine what to do next.)

The poster child for an overly clever non-zero exit status is expr, which will exit with status 1 if your expression evaluates to zero or to an empty string. This is not just silly, it is surplus; test (aka [) gives shell script authors a perfectly good way of testing the result of our expr expressions if we actually want this feature.

I am sure that a few shell script authors in the world have found this convenient over the years, but I am equally sure that a lot more shell script authors have wound up grimly guarding expr executions in various ways precisely because of this. Or with subtle bugs in their scripts because they were not guarding against the condition, because quick, who remembers that little expr landmine?

(Both have happened to us.)

Written on 08 July 2010.
« A gotcha with the Bourne shell's set -e and &&
People forget exceptions »

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

Last modified: Thu Jul 8 12:01:15 2010
This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.