CLI Option Handling

Every CLI program must: (1) error on unrecognised options, and (2) support --help / -h to print usage and exit 0. This applies regardless of language.

Rules

• Unknown/unrecognised options must produce an error message and exit non-zero. Never silently ignore them.

--help / -h must print a usage summary to stdout and exit 0.

• The help message must list every option with a one-line description and its default value where applicable.

Perl (Getopt::Long)

use Getopt::Long;

GetOptions(
    'help|h'   => \my $help,
    'option=s' => \my $option,
) or die "$0: unknown option. Try --help.\n";

if ($help) {
    print <<END;
Usage: $0 [options]

Options:
  --option VALUE    Description (default: foo)
  --help, -h        Show this help
END
    exit 0;
}

Python (argparse)

import argparse

parser = argparse.ArgumentParser(description='Tool description')
parser.add_argument('--option', default='foo', help='Description (default: %(default)s)')
args = parser.parse_args()  # exits with error on unknown args, --help built-in

Bash

usage() { echo "Usage: $0 [--option VALUE] [--help]"; exit 0; }

while [[ $# -gt 0 ]]; do
    case $1 in
        --option) OPTION=$2; shift 2 ;;
        --help|-h) usage ;;
        *) echo "$0: unknown option: $1" >&2; exit 1 ;;
    esac
done

Go

import "flag"

var option = flag.String("option", "foo", "Description")
flag.Parse()  // --help built-in; unknown flags cause error + usage

Rust (clap)

#[derive(Parser)]
struct Cli {
    /// Description
    #[arg(long, default_value = "foo")]
    option: String,
}
// clap generates --help and errors on unknown args automatically

C / C++

Use getopt_long(). Return ? from the switch to catch unknown options and print usage. Add 'h' / "help" explicitly.

version 1  ·  created 2026-06-12