Bash Getopts Subcommand Parsing

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

BashCli Tooling

Code

snippet
#!/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