开发者

getopts in bash programming

开发者 https://www.devze.com 2022-12-23 10:18 出处:网络
when i am using \'while getopts d:n: OPTION\' - how do i know that i got only invalid option and if yes that th开发者_Python百科ere is an argument after it?You know you have an invalid option because

when i am using 'while getopts d:n: OPTION' - how do i know that i got only invalid option and if yes that th开发者_Python百科ere is an argument after it?


You know you have an invalid option because the return value is '?'.

Either:

  • You can't tell whether it had an argument because the option was invalid.

Or:

  • You have to look at the next argument and see whether it starts with a dash.

The heuristic in the 'Or' option is imperfect. With option bundling, I could write:

command -xbf/fidget
  1. If the getopts option string is 'xf:', then the 'b' is the invalid option.
  2. If the getopts option string is 'xbf:', then there would be an option 'f' and the option argument '/fidget' after the valid option 'b'.
  3. If the getopts option string is 'xb:f:', then the option argument for 'b' would be 'f/fidget'.

I think the 'either' attitude is correct - you cannot tell.


Code fragment from a command called 'rcsunco' - to cancel RCS checkouts (and written at a time when I was reluctantly moving off SCCS):

remove=yes
keep=no
get=no
quiet=

while getopts gknqrV opt
do
        case $opt in
        V)  echo "`basename $0 .sh`: RCSUNCO Version $Revision: 2.1 $ ($Date: 2002/08/03 07:41:00 $)" |
            rcsmunger
            exit 0;;
        g)  get=yes;;
        k)  keep=yes;;
        n)  remove=no;;
        q)  quiet=-q;;
        r)  remove=yes;;
        *)  echo "Usage: `basename $0 .sh` [-{n|g}][-{r|k}] file [...]" 1>&2
            exit 1;;
        esac
done

shift $(($OPTIND-1))

These days, I'd used the 'balanced parentheses' notation in the 'case':

        (q) quiet=-q;;

Also note that I do not explicitly test which option is returned - I let the catchall '*' case deal. I also observe that the usage message is not complete (no '-V' or '-q' documented), and the code is old enough that I haven't added a '-h' for help option. The script 'rcsmunger' replaces '$Revision 2.1 $' with just '2.1', more like the way SCCS replaces '%I%' with '2.1'.


An invalid option will have a question mark ?... IIRC processing of the command line arguments processing stop if there's an question mark...

0

精彩评论

暂无评论...
验证码 换一张
取 消