-1

I want to use getopts but the default case doesn't work.

The code that I tried is:

while getopts "sdp" arg; do
case "$arg" in
s) 
    echo "1" 
;;
p)
    echo "2" 
;;
d) 
   echo "3" 
;;
*) 
   echo "default"
;;
esac

when I run the process: ./myTask

I didn't receive any output

omer blechman
  • 277
  • 2
  • 16
  • so what is the question. what do you want? – Dudi Boy May 30 '19 at 20:33
  • the default case doesn't work. – omer blechman May 30 '19 at 20:36
  • 2
    `getopts` returned zero status and the `while` loop never executed, thus the "default case" never executed. – KamilCuk May 30 '19 at 20:54
  • That's the default of the `case` statement, but it means something specific in the context of `getopts`: That you have an option defined but no clause to handle it. Please see a reference implementation of a `getopts` function in my answer [here](https://stackoverflow.com/a/11279500/26428). – Dennis Williamson May 30 '19 at 22:59

2 Answers2

2

It's working as intended.

The default case is not to handle the case where you don't have arguments, but the case where you supply invalid arguments:

$ ./myTest -X
./myTest: illegal option -- X
default

Normally you would write a usage message in this case.

that other guy
  • 116,971
  • 11
  • 170
  • 194
0

That's the default of the case statement, but it means something specific in the context of getopts: That you have an option defined but no clause to handle it.

If you run ./myTask -z, for example, you will see the output of "default" as @that_other_guy states in another answer here.

If you want to output something that indicates that no option was supplied:

Then after the while getopts block but before the shift $(($OPTIND - 1)) line, do this (with whatever processing you want inside the if block:

if ((OPTIND == 1))
then
    echo "No options specified"
fi

Note that this does not indicate that no arguments were specified (e.g. ./myTask as in your question). To do something with that, add this after the shift line:

if (($# == 0))
then
    echo "No positional arguments specified"
fi

Please see a reference implementation of a getopts function in my answer here.

Dennis Williamson
  • 346,391
  • 90
  • 374
  • 439