What is the best way to parse command line options

2019-08-06 21:03发布

问题:

So I have the following script to sort command line options I got it from here:

optstring=h
unset options #deletes options
while(($#));
do
echo $item;
case $1 in
   -[!-]?*) # caso a opção seja do tipo -ab
      for ((i=1; i < ${#1}; i++));do # Loop sobre cada caracter
         c=${1:i:1}
         options+=("-$c")
      if [[ $optstring = *"$c:"* && ${1:i+1} ]];
      then
            options+=("${1:i+1}")
            break
      fi
    done;;
    #type --foo=bar
    --*[^=*]) options+=("${1%%=*}") ;
              echo "${options[@]}";;

    #THIS ONE IS NOT WORKING IDK WHY
    --?*=*) options+=("${1%%=*}" "${1#*=}") ;
            echo "${options[@]}";;
    # adds --endopts for --
    --) options+=(--endopts) 
        echo "${options[@]}";;
    *) options+=("$1")
       echo "${options[@]}";;
  esac
  shift
done

And besides not working properly I feel that there is a better way to do this.
Can anyone point me in the right direction or at least tell me what I am doing wrong?

回答1:

Use shell built-in getopts or GNU command getopt.