Parse options and arguments in Bash scripts

8 steps · about 2 h 15 min · Intermediate

  1. Follow the standard utility argument conventions (reference, The Open Group, 15 min)

    POSIX defines how options, option-arguments and -- should behave, so your script matches users' expectations.

  2. Read the getopts specification (reference, The Open Group, 15 min)

    Defines OPTIND, OPTARG and silent error mode with a worked example.

  3. Compare getopts with a manual while loop (article, Greg's Wiki, 20 min)

    Shows both patterns, including long options, and the pitfalls of external getopt.

  4. Work with $1, $2, shift and set -- (article, The Linux Documentation Project, 15 min)

    Worked examples of positional parameters, which getopts and shift operate on.

  5. Use $#, $@ and $* correctly (reference, The Open Group, 20 min)

    The POSIX shell language section on special parameters explains why quoted "$@" preserves arguments with spaces.

  6. Know OPTIND, OPTARG and OPTERR (reference, man7.org, 15 min)

    The bash man page documents the variables getopts reads and sets, and the getopts builtin itself.

  7. Know when util-linux getopt is an option (reference, man7.org, 10 min)

    Supports long options but is not portable; the man page shows the safe eval pattern.

  8. Design helpful usage text and errors (article, clig.dev, 25 min)

    Command Line Interface Guidelines on help output, flags versus args and error messages.