Skip to content

Instantly share code, notes, and snippets.

@cgoldberg
Created August 1, 2025 03:26
Show Gist options
  • Save cgoldberg/3771a760ed965d7c4a2f5983a8248b70 to your computer and use it in GitHub Desktop.
Save cgoldberg/3771a760ed965d7c4a2f5983a8248b70 to your computer and use it in GitHub Desktop.
Bash - hack for `getopts` to handle a single short or long option with no args
#!/usr/bin/env bash
# this is a total hack for `getopts` so it handles a single short or long option
# - valid options are: -a, -h, --all, --help
# - no args for options are allowed
die () {
tput setaf 1; echo -en "\u2717 "; tput sgr0
tput bold; echo "$*" 1>&2; tput sgr0
exit 1
}
err_msg="fatal: only valid options are: -a, -h, --all, --help (with no args)"
while getopts ":ah-:" opt; do
if [[ -n "${!OPTIND+a}" ]]; then die "${err_msg}"; fi
if [ "${opt}" == "-" ]; then # long option: reformulate opt and OPTARG
opt="${OPTARG%%=*}" # extract long option name
OPTARG="${OPTARG#"${opt}"}" # extract long option arg
fi
case "${opt}" in
a | all )
OPT_ALL="true"
if [ -n "${OPTARG}" ]; then die "${err_msg}"; fi
;;
h | help )
OPT_HELP=true
if [ -n "${OPTARG}" ]; then die "${err_msg}"; fi
;;
\? | * )
die "${err_msg}"
;;
esac
done
if [ -n "${OPT_ALL}" ]; then
echo "-a or --all option was provided"
elif [ -n "${OPT_HELP}" ]; then
echo "-h or --help option was provided"
else
echo "no option provided"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment