Using getopts

I am having some trouble/questions with getopts that I can't find any solid info on with google

I need it to parse things of the syntax of:

-r # # # -f [word] [filename] -c [filename]

with as many repeats as possible, and it should catch erroneous commands also, but continue going...

my first question is, -r accepts 3 arguments. Does this mean I need 3 :'s when I do

while getopts r:f:c: o

also, what does the o in the above line represent exactly?

here is my code so far:

#! /bin/bash

while getopts r:f:c: o
do case "$o" in
	r)sh right.s $OPTARG $(( $OPTARG+1 )) $(( $OPTARG+2 ));;
	f)sh findtext.s $OPTARG $(( $OPTARG+1 ));;
	c)sh count.s $OPTARG;;
	?)echo "Useage: -r [#] [#] [#]"
		echo "	-f [key] [filename]"
		echo "	-c [filename]";;
esac
done

This doesnt work as desired. OPTARG holds the argument for the parsed option...... but since -r takes 3 arguments, does anyone know how to pass it the next THREE arguments? the above method adds 1 and 2 to the value of OPTARG.... :frowning:

Also, in regards to -c , if *.(extension) wildcards are passed, it only operates on the first one........why?

Is there a way to dereference OPTIND which holds the index of the argument to be parsed? Then I could dereference OPTIND, OPTIND+1 and OPTIND+2 to get the next 3 arguments properly passed...!

Thanks for reading! Any help is greatly appreciated :smiley:

Here is an example of using multiple optional arguments. All of them are in OPTARG.

#!/bin/ksh
# foo is shell function in this example - it could be a separate script
foo()
{
	echo "foo: I got $# options"	
	echo " they are $@"
}
while getopts a:  opt
do
  set -A arr $OPTARG
  case $opt in
    a) echo "option -a"
       for i in $OPTARG
       do
           echo "subargument = $i"         
       done
       echo "running foo with these options"
       foo $OPTARG
       exit 0 ;;
   \?) echo "\nUsage: $0 [-a <option>]" >&2
        exit 2;;
  esac
done

usage:

so you mean to tell me ALL I needed to do this whole time was encase all the arguments in quotation? It works perfect with them!... but is there a proper way to omit the quotes?

..... ??... .....

EDIT: This code block, if i give arguments to bad options, it immediatley exits the program instead of pressing onward

 #! /bin/bash

while getopts r:f:c: o
do case "$o" in
	r)sh right.s $OPTARG;;
	f)sh findtext.s $OPTARG;;
	c)sh count.s $OPTARG;;
	?)echo "Useage: -r ''[#] [#] [#]'' "
		echo "	-f ''[key] [filename]''"
		echo "	-c ''[filename]''";;
esac
done 

EDIT: While this works, if an invalid command is given arguments, it gives the ?) echo's, and then returns to the prompt, as opposed to pressing on if there are more arguments included....

did I miss something?

Hello

Try indirect expansion with !
First set A3 to the index of the 3rd argument and at the end increment OPTIND by 2

r) A3=$(( $OPTIND + 1 ))
sh right.s $OPTARG ${!OPTIND} ${!A3}
OPTIND=$(( $OPTIND + 2 )) ;;