Getopts Argument Parser With Validation

Parse command line options using bash getopts with validation, default values, and usage messages.

BashCli Tooling

Code

snippet
#!/usr/bin/env bash
set -euo pipefail

VERBOSE=0
OUTPUT=""
INPUT=""

usage() {
  echo "Usage: $0 [-v] [-o output] -i input" >&2
  exit 1
}

while getopts ":vo:i:" opt; do
  case "${opt}" in
    v) VERBOSE=1 ;;
    o) OUTPUT="${OPTARG}" ;;
    i) INPUT="${OPTARG}" ;;
    \?) echo "Unknown option: -${OPTARG}" >&2; usage ;;
    :) echo "Missing argument for -${OPTARG}" >&2; usage ;;
  esac
done

[[ -z "${INPUT}" ]] && usage
OUTPUT="${OUTPUT:-output.txt}"
[[ "${VERBOSE}" -eq 1 ]] && echo "Input: ${INPUT}, Output: ${OUTPUT}"