Getopt Long Options Parsing

Parse long and short options robustly with getopt, validating required flags, defaults, and positional arguments.

BashCli Tooling

Code

bashsnippet
38 lines
#!/usr/bin/env bash
set -euo pipefail

# 选项定义:短串加长定义,冒号表示需要参数
readonly SHORT="vo:t:"
readonly LONG="verbose,output:,timeout:"

PARSED=$(getopt --alternative --options "${SHORT}" \
  --longoptions "${LONG}" --name "$0" -- "$")
eval set -- "${PARSED}"

VERBOSE=false
OUTPUT="./out"
TIMEOUT=30

while true; do
  case "$1" in
    -v | --verbose)  VERBOSE=true; shift ;;
    -o | --output)   OUTPUT="$2"; shift 2 ;;
    -t | --timeout)
      [[ "$2" =~ ^[0-9]+$ ]] || { echo "超时须为数字: $2" >&2; exit 2; }
      TIMEOUT="$2"; shift 2 ;;
    --) shift; break ;;
    *) echo "未知参数: $1" >&2; exit 2 ;;
  esac
done

[[ $# -ge 1 ]] || { echo "用法: $0 [-v] [-o 输出] [-t 超时] <输入...>" >&2; exit 2; }

readonly TIMEOUT
readonly OUTPUT

echo "verbose=${VERBOSE} output=${OUTPUT} timeout=${TIMEOUT}"
for input in "$@"; do
  [[ -f "$input" ]] || { echo "输入不存在: ${input}" >&2; exit 1; }
  echo "处理 ${input} -> ${OUTPUT}"
done

Inside the snippet

Strict mode (set -euo pipefail) makes failures loud — an unset variable or a failing pipeline stage aborts the script instead of being swallowed.

The work is delegated to readonly and eval, chained through 9 pipes so each stage’s output feeds the next.

Points of care

  • The pipeline is 9 stages deep — when it misbehaves, split the pipe and test the stages separately.

The core lines of the flow

PARSED=$(getopt --alternative --options "${SHORT}" \
  --longoptions "${LONG}" --name "$0" -- "$")
while true; do
  case "$1" in
-v | --verbose)  VERBOSE=true; shift ;;

Interactive Tools for This Topic

FAQ

Does the script stop on the first error?
Yes — `set -euo pipefail` aborts on the first failing command, treats unset variables as errors, and fails the whole pipeline if any stage fails. Nothing continues half-broken.
Which external commands does the script rely on?
`readonly`, `eval` must be available on the PATH environment variable; everything else is shell built-in syntax.