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.
• 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.
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;
}
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
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
import "flag"
var option = flag.String("option", "foo", "Description")
flag.Parse() // --help built-in; unknown flags cause error + usage
#[derive(Parser)]
struct Cli {
/// Description
#[arg(long, default_value = "foo")]
option: String,
}
// clap generates --help and errors on unknown args automatically
Use getopt_long(). Return ? from the switch to catch unknown options and print usage. Add 'h' / "help" explicitly.