Thursday, 20 May 2010

Suppressing getopts unknown option error message in ksh

I'm writing a new ksh (Korn Shell) script today. Before this, I only write bash script, and I believe the knowledge that I gain today will be valuable to a lot of people.

When I'm trying to use getopts in ksh, the script complain that there are "unknown option" after I put some option that are not available.

Let see the code, and the way it respond.

user@computer $ cat -n getopts.sh
     1  #!/bin/ksh
     2
     3  while getopts "h" arg
     4  do
     5    case $arg in
     6      h)
     7        echo "Help!"
     8        ;;
     9      ?)
    10        echo "Others"
    11        ;;
    12    esac
    13  done

user@computer $ ./getopts.sh -h
Help!

user@computer $ ./getopts.sh -a
./getopts.sh[13]: -a: unknown option
Others

I expect when I put the option "-a", the script will just output "Others" without any issue. But it does not. Something is not correct with the code.

Searching the Internet for answer, I found this very informative site: http://aplawrence.com/Unix/getopts.html

At first read, the site did not specifically mentioned that you have to put leading ":" to suppress the errors, but after reading it the second time, I got the idea, especially after reading this word:

The leading ":" works like it does in "getopt" to suppress errors

So, to solve the issue, some minor modification has to be done to the script above. Let see the updated script and the output after the modification.

user@computer $ cat -n getopts.sh
     1  #!/bin/ksh
     2
     3  while getopts ":h" arg
     4  do
     5    case $arg in
     6      h)
     7        echo "Help!"
     8        ;;
     9      ?)
    10        echo "Others"
    11        ;;
    12    esac
    13  done

user@computer $ ./getopts.sh -h
Help!
 
user@computer $ ./getopts.sh -a
Others


Voila! The problem solved :)

Happy scripting :)