Skip to content

Instantly share code, notes, and snippets.

@Dreded
Last active March 21, 2024 05:04
Show Gist options
  • Save Dreded/eb89639754271761bcb655ed6086bf6e to your computer and use it in GitHub Desktop.
Save Dreded/eb89639754271761bcb655ed6086bf6e to your computer and use it in GitHub Desktop.
Bash argument parser
#!/usr/bin/env bash
# This is comment from here: https://stackoverflow.com/a/28466267
parseArgs() {
# just in case we call this twice make OPTIND local
local OPTIND OPT
die() { echo "$*" >&2; exit 2; } # complain to STDERR and exit with error
needs_arg() { if [ -z "$OPTARG" ]; then die "No arg for --$OPT option"; fi; }
# Defaults (to be thorough, you could also assign alpha="" and charlie="")
bravo="$HOME/Downloads" # Overridden by the value set by -b or --bravo
charlie_default="brown" # Only set given -c or --charlie without an arg
while getopts ab:c-: OPT; do # allow -a, -b with arg, -c, and -- "with arg"
# support long options: https://stackoverflow.com/a/28466267/519360
if [ "$OPT" = "-" ]; then # long option: reformulate OPT and OPTARG
OPT="${OPTARG%%=*}" # extract long option name
OPTARG="${OPTARG#$OPT}" # extract long option argument (may be empty)
OPTARG="${OPTARG#=}" # if long option argument, remove assigning `=`
fi
case "$OPT" in
a | alpha ) alpha=true ;;
b | bravo ) needs_arg; bravo="$OPTARG" ;;
c | charlie ) charlie="${OPTARG:-$charlie_default}" ;; # optional argument
\? ) exit 2 ;; # bad short option (error reported via getopts)
* ) die "Illegal option --$OPT" ;; # bad long option
esac
done
shift $((OPTIND-1)) # remove parsed options and args from $@ list
}
parseArgs "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment