getopts issue

Hi,
I have a script, that accepts two positional parameters. Now, I want to add one more optional parameter to it. But I do not want it to be an optional positional parameter as this will impact the future enhancement to the script. Hence I want to use getopts.

The script is now executed as follows:

./scriptname arg1 arg2 no_exit (where no_exit is the optional 3rd positional parameter)

I now want to execute the script as follows:

./scriptname arg1 arg2 -n (where -n is the optional parameter)

I am using the below code:

while getopts :n option
do
  case $option in
    n) no_exit=yes
  esac
done

This works if I execute the script in as

./scriptname -n arg1 arg2

but it does not work if I execute the script as

./scriptname arg1 arg2 -n

Any idea what modification has to be done to getopts to execute the script as

./scriptname arg1 arg2 -n

Thanks in advance.

getopts stop analyzing the arguments at the first one it doesn't recognize, so you need to give him only the optional arguments. This can be done with a shift.

arg1=$1
arg2=$2
shift 2
while getopts :n option
do
  case $option in
  n) no_exit=yes
  esac
done

Thanks a lot. It works.