Miguel M
Miguel M

Reputation: 370

What is the best way to parse command line options in bash shell?

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?

Upvotes: 1

Views: 648

Answers (1)

Alvaro Gutierrez Perez
Alvaro Gutierrez Perez

Reputation: 3877

Use shell built-in getopts or GNU command getopt.

Upvotes: 3

Related Questions