LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   ksh script Migrationfrom Solaris to Linux; getopts: arguments changed since last call (https://www.linuxquestions.org/questions/linux-newbie-8/ksh-script-migrationfrom-solaris-to-linux%3B-getopts-arguments-changed-since-last-call-931804/)

hmhoang04 02-28-2012 04:16 PM

ksh script Migrationfrom Solaris to Linux; getopts: arguments changed since last call
 
I am new to Unix scripting and trying to migrate a ksh from Sun Solaris to Linux. I got error " getopts: arguments changed since last call" when I executed the below sript in Linux. The script works fine in Sun Solaris though. Please note that the script uses getops in two places: the main routine and also in the notify function.



The function is: notify()
{
BOPT=0; LOPT=0; MOPT=0; POPT=0;

while getopts :blmp OPTION "$@"
do
case $OPTION in
b) BOPT=1 ;;
l) LOPT=1 ;;
m) MOPT=1 ;;
p) POPT=1 ;;
\?) ;;
esac
done

shift OPTIND-1
MSG=$*

if [ LOPT -eq 1 ];
then
log "$MSG"
fi

if [ POPT -eq 1 ];
then
msg "$MSG"
fi

if [ MOPT -eq 1 ];
then
email "$MSG"
fi

if [ BOPT -eq 1 ];
then
beep "$MSG"
fi

return;
}


The calling statement in the main is as follows:

##############################################################################
#
# MAIN ROUTINE
#
##############################################################################

HOST=`uname -n`
PROG=`basename $0`
ME=`whoami`
DT=`date '+%y%m%d'`
DATE=`date "+%Y-%m-%d %H:%M:%S"`

NODATAONLY="ON"

RESULT=
EXIT0=0
EXIT1=1
EXIT2=2
EXIT3=3

if [ $# -eq 0 ]; then
usage
fi

while getopts ":u:s:p:b:lnd" OPTM "$@"
do
case "${OPTM}" in
u) USER=${OPTARG};;
s) SID=${OPTARG};;
p) USERPASSWD=${OPTARG};;
b) BPERSON=${OPTARG};;
l) LOGTOSCREEN="ON";;
d) DEBUG="ON";;
*) notify -p "**ERROR : Invalid option -${OPTARG}"
usage;;
esac
done

set_def_vars;
set_env;
notify -l "Starting ${PROG} for ${USER}@${SID} ......"
.
.
.
.

kbp 02-28-2012 05:29 PM

Quote:

The shell does not reset OPTIND automatically; it must be manually reset between multiple calls to getopts within the same shell invocation if a new set of parameters is to be used.
.. this is from the bash man page, but I'm guessing it's probably the same as ksh in this case.

chrism01 02-28-2012 11:04 PM

Also add a shebang line to the top to ensure it uses your desired shell
Code:

#!/bin/ksh

# OR
#!/bin/bash

for RHEL based systems; your system may vary

hmhoang04 03-07-2012 07:58 AM

Hi kbp, chrism01,
I reset the OPTIND and it works. Many thanks for your help. I greatly appreciate it. Take care.
hmhoang04


All times are GMT -5. The time now is 11:27 PM.