According to Eric S. Raymond, one rule for Unix programming is the Rule of Silence: When a program has nothing surprising to say, it should say nothing. Since return codes are a form of information, I would like to add: when a program has carried out its task with no surprise, it should exit(0).
Take xscreensaver-command -lock
, for instance.
That command is meant to make a running XScreenSaver to lock the screen. I have
never seen it fail in doing so, however I sometimes get a non-zero code:
% xscreensaver -lock xscreensaver-command: could not frobnicate window 4212 zsh: exit 1 xscreensaver-command -lock
Well, xscreensaver-command
, I have the deep
regret to announce you that despite of your surprising return code, you
successfully succeeded to lock my screen. But that return code is wrong and
annoying. Wrong, because as a user, I do not care if xscreensaver-command -lock
failed to frobnicate some
window he would have loved to as long as it does its job and locks my screen.
To the user's point of view, locking the screen is binary: either it is done
and it is a success or it is not done and that is a failure. And it is
annoying, because it makes the return code meaningless and prevents you from
using it to do things like:
% # Lock screen and suspend to RAM (only if locking was successful) % xscreensaver -lock && sudo pm-suspend
With xscreensaver-command
sometimes returning a
non-zero code with no apparent reason, you end with a locked screen and your
computer still running, and have to unlock it and try again. This looks like
this meaningless dialogue:
- Scott to bridge.
- Kirk here. Scotty, could you restore impulse power?
- I'm sorry captain, I was not able to align the coaxial stabilizers, we just sustained too much damage here.
- How long would it take to get that power back?
- But you have it captain! Impulse power is working all right, it's just that…
- Good job Scotty, do you think will hold long enough?
- Well, I'd say it should hold until our next scheduled revision if we take care, but captain, I could not align…
So please, when you write a utility, design your return code for the user, not for you. If your utility has done the job, it should exit(0). What happened inside does may interest you as the developer but it does not matter to the user as long as the job is done, so it should not be reported to him, especially not with a misleading failure code.
3 comments
thursday 08 december 2011 à 22:58 Tanguy said : #1
friday 09 december 2011 à 00:05 Zack said : #2
friday 09 december 2011 à 08:38 Tanguy said : #3