Skip to content
systemcoding.dev
Systems Programming

Parse Command-Line Options with getopt

Learn how getopt walks argv in C, what optind, optarg and opterr mean, how a colon marks an option value, and how to handle errors and bundled flags.

8 min read
Summarize in AI
Flat illustration of user space above the system call boundary, the kernel and the hardware, with the C, Rust and Linux logos.

Every command-line program needs to read the words typed after its name, and doing it by hand goes wrong quickly. People bundle flags as -abc, attach values as -ofile, put -- before a file whose name starts with a hyphen, and expect sensible error messages for typos. The C library already has a parser for all of that, called getopt, and this post shows how to use it correctly with glibc 2.40 on Linux, following the rules in POSIX.1-2024. It is one part of the larger guide to building command-line tools in C, and it stops short of long options such as --help, which belong to getopt_long.

Words, options and operands

A program receives its arguments as an array of strings, argv, and a count, argc. The first string is the program's name. The rest fall into three kinds:

  • An option is a word that starts with a hyphen followed by one character, such as -v.

  • An option-argument is a value that belongs to an option, such as out.txt in -o out.txt.

  • An operand is everything else, usually the names of files to work on.

getopt understands the first two and leaves the third for you. It is declared in <unistd.h> as int getopt(int argc, char *const argv[], const char *optstring), and the full description is in getopt(3).

The call and its four globals

You call getopt repeatedly. Each call returns the next option character, and when options run out it returns -1. Four global variables carry the rest of the information.

VariableTypeMeaning
optargchar *The value of the option just returned, if it takes one
optindintIndex in argv of the next word to process, and of the first operand when parsing ends
opterrintIf nonzero (the default is 1), getopt prints its own error messages to stderr
optoptintThe option character that caused an error

The optstring argument lists the letters you accept. A letter followed by a colon takes a value. So "vo:n:" accepts -v with no value, and -o and -n each with one.

A first complete program

This program accepts -v for verbose, -o with an output file name, and -n with a number, and prints what it understood:

opts.cc
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
    int verbose = 0;
    const char *outfile = "a.out";
    long count = 1;
    int opt;

    while ((opt = getopt(argc, argv, "vo:n:")) != -1) {
        switch (opt) {
        case 'v':
            verbose = 1;
            break;
        case 'o':
            outfile = optarg;
            break;
        case 'n':
            count = strtol(optarg, NULL, 10);
            break;
        default:
            fprintf(stderr, "usage: %s [-v] [-o file] [-n count] [file ...]\n", argv[0]);
            return 2;
        }
    }

    printf("verbose=%d outfile=%s count=%ld\n", verbose, outfile, count);
    for (int i = optind; i < argc; i++)
        printf("operand %d: %s\n", i - optind + 1, argv[i]);
    return 0;
}

Run it as ./opts -v -o result.txt -n 3 a.txt b.txt and it prints:

Text
verbose=1 outfile=result.txt count=3
operand 1: a.txt
operand 2: b.txt

The same arguments written in a compact style, ./opts -vo result.txt -n3 a.txt b.txt, give identical output. Here -vo is a bundle of two options, with -o taking the next word as its value, and -n3 attaches the value to the option. getopt handles both forms because the option string says which letters take values. That freedom is the reason to use the library and not a loop over argv.

What the loop returns

The return value is an int, and it is one of four things.

  1. A valid option character, such as 'v'. If the option takes a value, optarg points at it.

  2. The character '?', when getopt met an option that is not in the option string, or an option that needs a value and has none. optopt holds the offending character.

  3. The character ':', but only if the option string begins with a colon, and only for a missing value.

  4. -1, when the options have ended.

With the default settings, getopt prints a message for case 2 before it returns, using the program name from argv[0]. A bad option gives:

Text
./opts: invalid option -- 'x'

and a missing value gives:

Text
./opts: option requires an argument -- 'o'

Both are followed by your default: branch, which prints the usage line and returns 2. The user therefore sees the specific complaint and then the correct form.

Handling errors yourself

If you want your own wording, set opterr = 0 before the loop, or begin the option string with a colon. With a leading colon, getopt stays silent and distinguishes the two failures, returning '?' for an unknown option and ':' for a missing value.

errs.cc
#include <stdio.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
    int opt;

    while ((opt = getopt(argc, argv, ":o:")) != -1) {
        switch (opt) {
        case 'o':
            printf("output: %s\n", optarg);
            break;
        case ':':
            fprintf(stderr, "%s: option -%c needs a file name\n", argv[0], optopt);
            return 2;
        case '?':
            fprintf(stderr, "%s: unknown option -%c\n", argv[0], optopt);
            return 2;
        }
    }
    return 0;
}

Running ./errs -o prints ./errs: option -o needs a file name on standard error and exits with status 2. Running ./errs -z prints ./errs: unknown option -z. Own messages are worth the extra lines when the tool is aimed at people who will read them, and the standard messages are fine for internal tools.

Operands and the double hyphen

When getopt returns -1, optind is the index of the first operand, and the operands run from there to argc - 1. A bare -- on the command line forces the end of options: getopt consumes it, returns -1 and sets optind just past it. That is how a user passes a file called -n to your program:

Text
./opts -v -- -n

prints verbose=1 outfile=a.out count=1 followed by operand 1: -n. A program that accepts file names should say in its help that -- works, because users who hit a hyphenated name need to know. A single hyphen is not an option at all, and getopt returns it as an operand, which is the convention for standard input.

glibc reorders, POSIX does not

POSIX says option parsing ends at the first operand. glibc does something friendlier by default: it permutes argv so that all options come first, wherever they appeared. With glibc, ./opts a.txt -v b.txt treats -v as an option and leaves a.txt and b.txt as operands, in their original order. On musl and the BSDs the same command stops at a.txt and passes -v through as an operand.

Two settings make glibc follow POSIX: set the environment variable POSIXLY_CORRECT, or start the option string with +, as in "+vo:n:". A tool that runs on several systems should choose one behaviour and write it down, because scripts that rely on options after operands break on any system that does not permute. The safe habit for callers is to put options before operands.

A related trap is the combination of the + prefix and the : prefix. To get both strict stopping and silent errors, write "+:o:". The order of the two prefix characters matters: the plus comes first.

Converting option values safely

optarg is a string, and turning it into a number needs care. atoi silently returns 0 for garbage, and the first example above used strtol with no error check, which is no better. A reliable conversion checks both that digits were consumed and that nothing is left over:

parse_num.cc
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>

int parse_count(const char *s, long *out)
{
    char *end;

    errno = 0;
    long v = strtol(s, &end, 10);
    if (errno != 0 || end == s || *end != '\0' || v < 0 || v > INT_MAX)
        return -1;
    *out = v;
    return 0;
}

The three checks catch overflow (errno set by strtol), an empty or non-numeric string (end == s), and trailing junk such as 12abc (*end != '\0'). The range test rejects negative counts and values too big for an int. A tool that gets a bad value should print which option was wrong and exit with status 2, since a bad value is a usage error and not a runtime failure.

Repeated options and last-one-wins

The loop sees every occurrence in order. For a flag, repeating it is harmless. For an option with a value, the usual rule is that the last one wins, which is what the example does by assigning outfile = optarg. Some tools count repeats, as in -v -v for more verbosity, and the loop does that with verbose++. Others collect all the values into an array, as -I does for a compiler. Decide what repetition means, and document it. Accepting a repeat silently when it means nothing is how conflicting arguments slip into scripts.

Re-parsing and thread safety

getopt keeps its place in static state, optind and an internal pointer into the current bundle. That has two consequences. It is not thread-safe, which is fine because parsing happens once at startup. And if you want to parse a second array, such as options read from a file or an environment variable, you must reset optind to 1 first. glibc also needs the internal state cleared, which setting optind = 0 does as a documented extension. Setting it to 1 alone works for the common case on other systems. The cleaner design is to build one combined argv and parse it once.

When getopt is not enough

getopt is a good fit for a tool with a few single-letter flags. It is the wrong tool in four situations:

  • Long options. --output=file needs getopt_long, or a hand-written parser.

  • Subcommands. A tool such as git commit -m msg has options for the program and options for the subcommand. Parse the global options with getopt using the + prefix so it stops at the subcommand name, then give the rest to the subcommand's own loop after resetting optind.

  • Options with optional values. A double colon, as in "o::", is a GNU extension and means -ofile carries a value but -o file does not. It surprises users and is not available on musl or the BSDs, so avoid it.

  • Windows. The Microsoft C runtime has no getopt, and a tool that must build there needs a bundled copy or another parser.

Share

Keep reading

Flat illustration of two options weighed side by side, with the macOS, Linux and Apple logos.
Kernels

Mach Traps vs BSD System Calls on macOS

Learn how macOS routes one trap instruction to either a Mach trap or a BSD system call, how the number sign and class decide, and why you should call libSystem.

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