Skip to content
systemcoding.dev
Systems Programming

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.

1 min read
Summarize in AI

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.

usage.cc
#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;
}
Text
$ ./tool -x file
./tool: invalid option -- 'x'
usage: ./tool [-v] [-n count] file
$ echo $?
2

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

Taggedcposix
Share

More snippets

Systems Programming

Get the page size with sysconf(_SC_PAGESIZE)

Read the memory page size at run time with sysconf(_SC_PAGESIZE) instead of hard-coding 4096, which is wrong on arm64 kernels built with 16K or 64K pages.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.