[KornShell]: Why getopts doesn't detect disabled switches in this script?

Hi,

My environement

OS:           Linux Fedora Core 17 X86_64
KSH version:  sh (AT&T Research) 93u+ 2012-08-01

As I understand inside a Kornshell script, the getopts statement allows to collect information about the switches provided for the script (if any). Besides, it is possible to enable/disable those switches respectively by preceding each switch letter with either - or +.

I just wanted to see this in pratice. Therefore I wrote the following code which unfortunately does not give the expected output.

#!/usr/bin/ksh
while getopts :xy arguments
do
    case $arguments in
        x)
            print "x on"
            ;;
        +x)
            print "x off"
            ;;
        y)
            print "y on"
            ;;
        +y)
            print "y off"
            ;;
        \?)
            print "unknown switch"
            ;;
    esac
done

And here is what I get when I run the above script in my linux terminal (myscript.ksh is the name of my script)

$ ./myscript.ksh -x
x on
$ ./myscript.ksh +x
$ ./myscript.ksh -y
y on
$ ./myscript.ksh +y
$ 

As you can see whenever a switch is preceded by - (therefore enabled) the script prints the corresponding message but whenever it is preceded by the + (disabled) the scripts doesn't seem to do anything and there is no message printed.

Could you kindly help me understand the problem in my script?

Thanks in advance,

Could you point out where in the manual page it shows that getopts treats arguments as switches (+x / -x) and not options (-x)?

With 1993 and laters versions of ksh , getopts will handle both + and - if you tell it you want it to do that. Change:

while getopts :xy arguments

to:

while getopts +:xy arguments

or:

while getopts :+xy arguments

The November 16, 1988 version of ksh behaved as if the first character of the option string was always '+'.

2 Likes

Dear Don, thank you very much for your help which solved the problem! :b:

In fact I saw the use of getopts for switches in the book "KornShell Programming Tutorial" written by Barry Rosenberg for the first time. The author had used :xy and not :+xy. Therefore, either the example in the book had been written for an older version of KSH or simply a typo.

Anyway, thanks to your remark I learnt a new thing today & now the example works.

Thank you very much for your help. :slight_smile:

Regards,