Last active
December 26, 2022 07:40
-
-
Save SomajitDey/fcc5b64783e0d2ed93557bd95d76dac8 to your computer and use it in GitHub Desktop.
Parse GNU style long options (--opt optarg | --opt=optarg) as well as short Unix options (-ooptarg | -o optarg). Source: https://stackoverflow.com/a/28466267.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 ab: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 | |
a | alpha ) alpha=true ;; | |
b | bravo ) needs_arg; bravo="$OPTARG" ;; | |
c | charlie ) needs_arg; charlie="$OPTARG" ;; | |
??* ) die "Illegal option --$OPT" ;; # bad long option | |
? ) exit 2 ;; # bad short option (error reported via getopts) | |
esac | |
done | |
shift $((OPTIND-1)) # remove parsed options and args from $@ list |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment