Skip to content

Instantly share code, notes, and snippets.

@larryv
Last active August 23, 2016 20:03
Show Gist options
  • Save larryv/ffc60f11d7a7133996218177e1612856 to your computer and use it in GitHub Desktop.
Save larryv/ffc60f11d7a7133996218177e1612856 to your computer and use it in GitHub Desktop.
A small function that uses enhanced getopt(1) to define parameters
parseopt() {
[[ -n $1 ]] || return 1
# Use "--options +" to prevent arguments from being rearranged.
local -r opts=$(getopt --name "$0" --options + --longoptions "$1" -- "${@:2}")
case $((10#$?)) in
1)
# getopt(1) will print an error first.
echo >&2 "Try \`$0 --help' for more information."
return 2
;;
[!0]*)
errmesg 'Internal error while parsing options'
return 4
;;
esac
local -a validopts
IFS=, read -ar validopts <<<"$1"
readonly validopts=("${validopts[@]/#/--}")
eval set -- "$opts"
local opt validopt
# getopt(1) ensures that the options are always terminated with "--".
while [[ $1 != -- ]]; do
opt=$1
shift
# XXX Do NOT touch anything below unless you know exactly what
# you're doing (http://mywiki.wooledge.org/BashFAQ/006#eval).
for validopt in "${validopts[@]}"; do
if [[ $validopt == "${opt}:" || $validopt == "${opt}::" ]]; then
opt=${opt#--}
# $1 is null for omitted optional arguments.
eval 'option_'"${opt//-/_}"'=$1'
shift
continue 2
fi
if [[ $validopt == "$opt" ]]; then
opt=${opt#--}
eval '(( ++option_'"${opt//-/_}"' ))'
continue 2
fi
done
# Unreachable unless there is a bug in this function or in getopt(1).
errmsg 'Internal error while parsing options'
return 4
done
remaining_args=("${@:2}")
}
# Process options.
declare -a remaining_args
parseopt archive-site:,help,port:,prefix:,svn:,svn_revision:,svn_url:,staging-dir:,variants:,workdir: "$@" || exit $?
set -- "${remaining_args[@]}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment