0

I have the following bash function that uses getopts to parse positional arguments. Am trying to make options fail and get to print error messages.

pfa ()
{
 local OPTIND OPTARG
 local shortopts=":Vuhv:f:sc:"
 while getopts $shortopts arg; do
   case $arg in    
    ("f")  fvar="$OPTARG" ;;
    ("c")  cnum="$OPTARG" ;;
    ("s")  sort=1 ;;
    (":")  
      printf '%s\n' ": Argument not supplied to -${OPTARG}" 
      break
      ;;
    ("?") 
      printf '%s\n' "? Option not recognised by shortopts"
      break
      ;;
    (*)
      printf '%s\n' "Invoke \`pfa -h' for details."
      ;;
   esac
 done
}

I am running the two commands below, one with an unrecognised -g and another with a missing argument value to -g. The problem is that when using -f, it is not tollingg me that the argument value has not been supplied.

tolu@flora: ~
pfa -g -c 200
? Option not recognised by shortopts

tolu@flora: ~
pfa -f -c 200

tolu@flora: ~
pfa -c 200 -f
: Argument not supplied to -f
Dilna
  • 405
  • 1
  • 6
  • In the second case, `-f` *does* have an argument -- it's the `-c` (check the value of `$fvar` after the loop). `-c` might *look* like a separate option, but since `-f` takes an argument, it's where the argument to `-f` belongs, and there's no reason an option argument cannot start with `-`, it's treated as the argument to `-f`. – Gordon Davisson Oct 31 '21 at 16:53
  • The only way to get `Argument not supplied to -f` is to run `pfa -f` – Philippe Oct 31 '21 at 17:34
  • You are right, `:` only works if it is at the end. Not very useful in practice from what I see. Does not even work with `pfa -c 200 -f -- "deiu"`. I was also hoping `-f` would see that `-c` starts another option, which it does not. – Dilna Oct 31 '21 at 17:59
  • I have the variable `shortopts=":Vuhv:sc:w:o:"` and want to remove the leading `:`. How can I get that? – Dilna Nov 01 '21 at 04:03

0 Answers0