Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
943 views
in Technique[技术] by (71.8m points)

linux - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use shell built-in getopts or GNU command getopt.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...