0

I am using getopts and have the intention of using an option -v which can take an optional argument.

When using getopt isnstead of getopts, people customarily use the shift command to go to the next argument. But I do not see people use shift when using getopts.

 local vb=1  sort=0

 local OPTIND OPTARG
 local shortopts="Vuhvs"
 while getopts $shortopts arg; do
   case $arg in
     ("V") printf '%s\n' "Version" ; return ;;
     ("u") printf '%s\n' "usage"   ; return ;;
     ("h") printf '%s\n' "help"    ; return ;;
     ("v")
       # Allows argument to be optional.
       # Defines option with no arguments in shortopts.
       nextarg=${!OPTIND}
       if [[ (-n "$nextarg") && ("$nextarg" != -*) ]] ; then
         OPTIND=$((OPTIND + 1))
         vb="$nextarg"
       fi
       ;;
     #.............................
     ("s") sort=1 ; shift ;;         # shifts arg by 1
     #.............................
     (?)
       pfm "Invalid option: -${OPTARG}."
       pfm "Invoke \`linge-pfa -h\` for details."
       break
       ;;
   esac
 done
Nigel
  • 39
  • 4
  • 1
    `getopts` does not support optional arguments to options. – chepner Aug 26 '21 at 20:26
  • So there are no work-arounds with it ? – Nigel Aug 26 '21 at 20:39
  • 1
    No; either you declare the option with `:`, and failing to provide an argument is an error, or you don't, and providing an argument is an error. – chepner Aug 26 '21 at 20:41
  • Thusly, got to parse yourself. – Nigel Aug 26 '21 at 20:44
  • 1
    There are other libraries you can use. For example, GNU `getopt` supports optional arguments, as does https://github.com/docopt/docopts. – chepner Aug 26 '21 at 20:49
  • https://stackoverflow.com/questions/11517139/optional-option-argument-with-getopts https://stackoverflow.com/questions/23944283/using-getopts-in-bash-to-get-optional-input-argument?noredirect=1&lq=1 – KamilCuk Aug 26 '21 at 20:53
  • Does not one use `shift` to move to the next option after reading an option argument ? – Nigel Aug 27 '21 at 23:42

0 Answers0