Unix command line utility program conventions

Sometimes a vendor supplies a command-line utility for performing some function that we want to use from within our scripts and programs.

There are some unwritten (at least as far as I can find) rules about how to write one of these utilities so it can be used properly.

Some vendors get this right. Others, not so much…

The Rules

Return an error status indicating success or failure. For bonus points, return multiple different error codes depending on what went wrong. (The Anna Karenina Principle)

And you know what? That’s about it. The rest (arguments, input/output locations, etc., etc.) really depends on the context and function of the item in quesiton. Though the following are useful:

  • Provide a useful usage message if invalid arguments are passed.
  • Provide an explict way (e.g. –help option) to ask for the above usage message.
  • Use GNU-style arguments.

But these are really for human consumption, not for use in a script.

Recent Failures

I won’t name names, but here are some of the failures I’ve seen recently. (And these are from Big Companies that should know better. Including one company that actually has its own version of Unix… they should really know better.)

  • utility always returns status 1. How the HECK am I supposed to know if it worked? Why are you always returning failure? Didn’t you read a single Unix man page? Didn’t you notice that non-zero exit codes mean failure?
  • -q option suppresses error messages to stdout/stderr… and suppresses the error code return as well. Take a look at diff(1) sometime. The -q option just suppresses the listing of the differences, but still returns the error code.

Strangely enough, these rules apply equally well to Windows command-line utilities. Yes, these do exist.

Another suggestion

If it can be done with a command-line utiltiy, then give us an API we can use.

If you even just create a simple C library, we can then wrap it into our favorite language as a Perl Extension Module, or a Java Native Interface (JNI) pacakge.

If you feel like creating a pure Java implementation of the Library, that would be good too.

From Dan Moore:

On a different tack, but still touching some of the same principles, you may want to check out the Command-Line Options section of the Art of Unix Programming

Originally Posted June 7, 2004 11:20 AM

Leave a Reply