Interview Prep/Shell Scripting/Arguments, I/O, here-docs, process substitution and subshells

How does `getopts` work? Show a complete example.

IntermediateConceptArguments, I/O, here-docs, process substitution and subshells
Answer

getopts OPTSTRING VAR parses short options one at a time. A letter followed by : takes an argument (in $OPTARG). A leading : in the optstring enables silent mode, where you handle errors yourself: ? for unknown options, : for a missing argument.

env="" verbose=0
while getopts ':e:vh' opt; do
  case $opt in
    e) env=$OPTARG ;;
    v) verbose=1 ;;
    h) usage; exit 0 ;;
    :) echo "option -$OPTARG requires an argument" >&2; exit 2 ;;
    \?) echo "unknown option -$OPTARG" >&2; exit 2 ;;
  esac
done
shift $((OPTIND - 1))        # "$@" is now the non-option arguments
[[ -n $env ]] || { echo "-e is required" >&2; exit 2; }

getopts supports bundling (-ve prod) and stops at -- or the first non-option.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Arguments, I/O, here-docs, process substitution and subshells