1

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?

Miguel M
  • 302
  • 3
  • 16
  • Do you want to parse the user input or command line options? – ramana_k Oct 11 '15 at 01:14
  • Sorry! Command line options. – Miguel M Oct 11 '15 at 01:21
  • 2
    A number of options are listed in [Bash FAQ 035](http://mywiki.wooledge.org/BashFAQ/035). – Etan Reisner Oct 11 '15 at 01:29
  • 2
    try searching here about `[bash] getopts`, or if you knew about getopts, you might want to explain why your don't want to use it. Good luck! – shellter Oct 11 '15 at 02:02
  • Not sure from your question whether you just want to parse or sort in particular. Anyways if you just want to parse the command line options apart from the `getopts` as mentioned above you have one more option of `docopts` which I find very convenient. All you have to do is write a help message and supply it to docopts, it will parse the command line options. If this answers let me know i will add as answer with example. [check](http://docopt.org/) – Sagar Masuti Oct 11 '15 at 03:38
  • [How do I parse command line arguments in Bash?](https://stackoverflow.com/q/192249/608639), [How to iterate over arguments in a Bash script](https://stackoverflow.com/q/255898/608639), [Best way to parse command line args in Bash?](https://stackoverflow.com/q/14786984/608639), [What is the best way to parse command line options in bash shell?](https://stackoverflow.com/q/33060602/608639), [Parsing shell script arguments](https://stackoverflow.com/q/4882349/608639), etc. – jww Apr 12 '18 at 19:58

1 Answers1

3

Use shell built-in getopts or GNU command getopt.

Alvaro Gutierrez Perez
  • 3,669
  • 1
  • 16
  • 24