Skip to content

Instantly share code, notes, and snippets.

@adrian7
Created December 12, 2021 08:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adrian7/35e7de6feb74828c4a18b780ef063c34 to your computer and use it in GitHub Desktop.
Save adrian7/35e7de6feb74828c4a18b780ef063c34 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
# Example of supporting long (--long) and short (-s) options in bash via getopts
# Shorg options are declared at the beginning of the while block,
# while their counterparts (long options) are declared in the case block
# If the option requires a value, it should be declared as r: (letter followd by colon)
# and validated with needs_arg() when parsing.
# Alternatively die "Error message" is used to stop when we get an option which has not been declared
# Source: https://stackoverflow.com/a/28466267/319150
# Example usage:
# ./getopt.sh -f -b bravo
# ./getopt.sh --alpha ABC
# ./getopt.sh --charlie="menu1" --bravo="bravissimo" -a first
# ./getopt.sh -c "the value for 'charlie' option" -f
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; }
while getopts afb:c:-: OPT; do
# 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
f ) filter=true ;;
a | alpha ) alpha=true ;;
b | bravo ) needs_arg; bravo="$OPTARG" ;;
c | charlie ) needs_arg; charlie="$OPTARG" ;;
??* ) die "No such option --$OPT. See $0 --help for details." ;; # bad long option
? ) exit 2 ;; # bad short option (error reported via getopts)
esac
done
shift $((OPTIND-1)) # remove parsed options and args from $@ list
printf "Your input: filter=%s\talpha=%s\tbravo=%s\tcharlie=%s\n" "$filter" "$alpha" "$bravo" "$charlie"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment