Print usage and exit with status 2 on bad options
Print a usage line to stderr and exit with status 2 on a bad option, the convention used by grep, getopt and most Unix tools, in C.
When a user passes an option the program does not know, there is a better exit status than 1. Most tools reserve 1 for "ran fine, found nothing" or a runtime failure and use 2 for a command-line mistake, which is what GNU grep documents in its exit status section. That lets a script tell a bad invocation from a failed run.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
static void usage(const char *prog) {
fprintf(stderr, "usage: %s [-v] [-n count] file\n", prog);
exit(2);
}
int main(int argc, char **argv) {
int opt;
while ((opt = getopt(argc, argv, "vn:")) != -1) {
switch (opt) {
case 'v': break;
case 'n': break;
default: usage(argv[0]);
}
}
if (optind >= argc) usage(argv[0]);
return 0;
}$ ./tool -x file
./tool: invalid option -- 'x'
usage: ./tool [-v] [-n count] file
$ echo $?
2getopt prints the first line itself and returns ?, so the default branch only adds the usage. Send usage errors to stderr, not stdout, so a pipe stays clean. A successful --help is different: print to stdout and exit 0. Name argv[0] in the message, as above, so the text still makes sense when the tool is run through a symlink or a wrapper script.