Skip to content

Instantly share code, notes, and snippets.

@nhoriguchi
Created September 6, 2012 19:10
Show Gist options
  • Save nhoriguchi/3659587 to your computer and use it in GitHub Desktop.
Save nhoriguchi/3659587 to your computer and use it in GitHub Desktop.
Getopts Wrapper
#!/bin/bash
# Extended version of getopts, which cannot handle both optional/non-optional
# parameters in a combined manner (non-optional ones can't come first.)
# This function allows us to do it and we can parse all of the followings:
# ./cmd -a optarg_for_a -b arg1
# ./cmd -a optarg_for_a arg1 -b
# ./cmd arg1 -a optarg_for_a -b
#
# The usage of getopts_extended is similar to that of getopts like:
# getopt_extended "ab:c" [retcode] "$@"
#
# Note:
# - the last argument for getopt_extended should be double-quoted,
# otherwise long non-optional arguments (strings with multiple words
# like "a b c") are considered as separated.
# - getopts_extended returns '?' when non-optional arguments come,
# then parsed arguments is stored in OPTARG.
getopts_extended() {
local optstring=$1
local retcode=$2
shift 2
local argnum=$#
# Return if we already finished up argument parsing.
[ $OPTIND -gt $argnum ] && return 1
getopts $optstring $retcode $@
local ret=$?
if [ $ret -ne 0 ] ; then # for non-optional arguments
eval OPTARG=\${$OPTIND}
words=`echo $OPTARG | wc -w`
OPTIND=$[OPTIND + words]
fi
return 0
}
while getopts_extended "a:b" opt "$@" ; do
case $opt in
a) echo "opt -a $OPTARG" ;;
b) echo "opt -b $OPTARG" ;;
\?) echo "args [$OPTARG]"
esac
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment