Parse Options With getopts
Parse short options and their arguments with getopts so a shell script exposes a predictable CLI instead of positional guesswork.
Code
#!/usr/bin/env bash
set -euo pipefail
verbose=false
output=""
level=1
while getopts ":vo:l:h" opt; do
case "${opt}" in
v) verbose=true ;;
o) output="${OPTARG}" ;;
l)
level="${OPTARG}"
if ! [[ "${level}" =~ ^[1-9]$ ]]; then
echo "level must be 1-9" >&2
exit 2
fi
;;
h)
echo "usage: $0 [-v] [-o output] [-l level] input"
exit 0
;;
:)
echo "option -${OPTARG} requires an argument" >&2
exit 2
;;
\?)
echo "unknown option: -${OPTARG}" >&2
exit 2
;;
esac
done
shift $((OPTIND - 1))
input="${1:?input file is required}"Report a problem with this exampleOpens a pre-filled issue on GitHub.