ksh: can you use getopts in a function?

I wrote a script that uses getopts and it works fine. However, I would like to put the function in that script in a startup file (.kshrc or .profile). I took the "main" portion of the script and made it a function in the startup script. I source the startup script but it doesn't seem to parse through the getopts case.

So my question is if using getopts in a function is even valid?

Thanks.

Specify the arguments of the script to the function :

# Call the function to parse arguments with getopts
my_function "${@}"

Jean-Pierre.

I have a number of functions in .bashrc

One function I'll call hctinfo() and it is considered by me to be the "main" part of my set of functions. It calls other functions depending on the options (handled by getopts.

Looks like this:

version()
{
...
}
usage()
{
...
}
help()
{
...
}
getAdminStatus()
{
...
}
getOperStatus()
{
...
}
getDescription()
{
...
}
getImage()
{
...
}
getGroup()
{
...
}
getMod()
{
...
}
getPackages()
{
...
}
hctinfo()
{
        ADMIN_STAT=0
        GROUP=0
        IMAGE=0
        DESC=0
        MOD=0
        OPER_STAT=0
        PACKS=0
        OPTSTRING=":aAdDhHiIgGmMoOpPvV"
        while getopts ${OPTSTRING} option
        do
                case ${option} in
                        h|H)    help
                                return 0;;
                        v|V)    version
                                return 0;;
                        a|A)    printf "ADMIN_STAT=1\n"
                                ADMIN_STAT=1;;
                        i|I)    IMAGE=1;;
                        g|G)    GROUP=1;;
                        d|D)    DESC=1;;
                        m|M)    MOD=1;;
                        o|O)    OPER_STAT=1;;
                        p|P)    PACKS=1;;
                        ?)      printf "\nWTF? Way to go, dumbass.\n\n"
                                usage
                                return 1;;
                esac
        done

        shift $(($OPTIND - 1))
...
...
}

The first time I log in to the system and source the file that has the functtions define and run it, it works. Each subsequent time I attempt to run it it fails to parse the options.

$ . ./.bashrc
Sun Microsystems Inc.   SunOS 5.10      Generic January 2005
\nWorking directory is /dvs/dncs\nDatabase is dncsdb\n
[14:00:22]$ hctinfo -a 00:40:7B:E1:AB:66
ADMIN_STAT=1
  Deployed
[14:00:26]$ hctinfo -a 00:40:7B:E1:AB:66
[14:00:32]$ 

I think I know what the problem is...

Somehow the options, options count, etc... (everything associated with getopts) needs to get reset.

Any ideas?

You could unset the getopts variables at the end of your script.

unset $OPTSTRING
unset $OPTIND
etc...

You are a genius. Thanks.