Add 'Parse command line options.sh'
This commit is contained in:
24
Parse command line options.sh
Normal file
24
Parse command line options.sh
Normal 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
|
||||
Reference in New Issue
Block a user