Add 'Parse command line options.sh'

This commit is contained in:
2024-01-26 12:21:17 +01:00
parent 53fd49cc5c
commit 5db29434f5

View File

@ -0,0 +1,24 @@
# Parse command line options
# =========================================================================== #
# This is an example script for using both long and short flags without using getopt (which is nonstandard)
# Copy paste from
# https://stackoverflow.com/questions/402377/using-getopts-to-process-long-and-short-command-line-options
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
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=true ;;
??* ) 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