index : pacman | |
Archlinux32 fork of pacman | gitolite user |
summaryrefslogtreecommitdiff |
author | Allan McRae <allan@archlinux.org> | 2011-06-08 23:36:46 +1000 |
---|---|---|
committer | Dan McGee <dan@archlinux.org> | 2011-06-15 09:16:38 -0500 |
commit | 6f3a2145b0de7f27a1bf5932af3fe0a67171a881 (patch) | |
tree | 675413c6ba4b2ecdfc7aea7c6b0c053c6b52f843 /scripts/library | |
parent | 5f404f2cb78f48ddd90be0334fa2528961b17871 (diff) |
-rw-r--r-- | scripts/library/parse_options.sh | 87 |
diff --git a/scripts/library/parse_options.sh b/scripts/library/parse_options.sh new file mode 100644 index 00000000..32aa0bee --- /dev/null +++ b/scripts/library/parse_options.sh @@ -0,0 +1,87 @@ +# getopt like parser +parse_options() { + local short_options=$1; shift; + local long_options=$1; shift; + local ret=0; + local unused_options="" + local i + + while [[ -n $1 ]]; do + if [[ ${1:0:2} = '--' ]]; then + if [[ -n ${1:2} ]]; then + local match="" + for i in ${long_options//,/ }; do + if [[ ${1:2} = ${i//:} ]]; then + match=$i + break + fi + done + if [[ -n $match ]]; then + if [[ ${1:2} = $match ]]; then + printf ' %s' "$1" + else + if [[ -n $2 ]]; then + printf ' %s' "$1" + shift + printf " '%s'" "$1" + else + echo "@SCRIPTNAME@: option '$1' $(gettext "requires an argument")" >&2 + ret=1 + fi + fi + else + echo "@SCRIPTNAME@: $(gettext "unrecognized option") '$1'" >&2 + ret=1 + fi + else + shift + break + fi + elif [[ ${1:0:1} = '-' ]]; then + for ((i=1; i<${#1}; i++)); do + if [[ $short_options =~ ${1:i:1} ]]; then + if [[ $short_options =~ ${1:i:1}: ]]; then + if [[ -n ${1:$i+1} ]]; then + printf ' -%s' "${1:i:1}" + printf " '%s'" "${1:$i+1}" + else + if [[ -n $2 ]]; then + printf ' -%s' "${1:i:1}" + shift + printf " '%s'" "${1}" + else + echo "@SCRIPTNAME@: option $(gettext "requires an argument") -- '${1:i:1}'" >&2 + ret=1 + fi + fi + break + else + printf ' -%s' "${1:i:1}" + fi + else + echo "@SCRIPTNAME@: $(gettext "invalid option") -- '${1:i:1}'" >&2 + ret=1 + fi + done + else + unused_options="${unused_options} '$1'" + fi + shift + done + + printf " --" + if [[ -n $unused_options ]]; then + for i in ${unused_options[@]}; do + printf ' %s' "$i" + done + fi + if [[ -n $1 ]]; then + while [[ -n $1 ]]; do + printf " '%s'" "${1}" + shift + done + fi + printf "\n" + + return $ret +}
\ No newline at end of file |