Bash Getopts Subcommand Parsing

Parse CLI subcommands and options with getopts for shell script tooling.

BashCli Tooling

Code

bashsnippet
22 lines
#!/bin/bash
subcommand="$1"; shift
case "$subcommand" in
  serve)
    port=8080
    while getopts ":p:" opt; do
      case "$opt" in
        p) port="$OPTARG" ;;
        \?) echo "unknown: -$OPTARG" >&2; exit 1 ;;
      esac
    done
    echo "serving on port $port"
    ;;
  build)
    output="dist"
    while getopts ":o:" opt; do
      case "$opt" in o) output="$OPTARG" ;; esac
    done
    echo "building to $output"
    ;;
  *) echo "usage: $0 {serve|build}" >&2; exit 1 ;;
esac

How the snippet works

Option parsing walks the argument list explicitly, so flags, their values, and positional arguments are handled in one place.

Applying it

The script self-documents: the help branch prints $0 {serve|build}.

Flags are consumed by the option loop and positional arguments are read after it, so script -v -o out input and script input both behave predictably.

Statements that matter most here

while getopts ":p:" opt; do
  case "$opt" in

Interactive Tools for This Topic