Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the OPTIND variable work in the shell builtin getopts

My shell script is quite simple, as the following:

  while getopts "abc:" flag; do
         echo "$flag" $OPTIND $OPTARG
  done

And I do some testing as the following:

Blank@Blank-PC:~/lab/shell/getopts_go$ sh foo.sh -abc CCC Blank
a 1
b 1
c 3 CCC

Blank@Blank-PC:~/lab/shell/getopts_go$ sh foo.sh -a -b -c CCC Blank
a 2
b 3
c 5 CCC

Blank@Blank-PC:~/lab/shell/getopts_go$ sh foo.sh -ab -c CCC Blank
a 1
b 2
c 4 CCC

Blank@Blank-PC:~/lab/shell/getopts_go$ sh foo.sh -a -bc CCC Blank
a 2
b 2
c 4 CCC

I cannot understand how OPTIND works with different command line invocation, I am confused by the output.

Can you help to figure out the mechanism of computing OPTIND?

like image 643
Blank Avatar asked Jan 10 '13 02:01

Blank


People also ask

What is Optind in getopts?

According to man getopts , OPTIND is the index of the next argument to be processed (starting index is 1).

What does getopts mean in Bash?

On Unix-like operating systems, getopts is a builtin command of the Bash shell. It parses command options and arguments, such as those passed to a shell script. How it works. Specifying the optstring. Verbose error checking.

What does shift (( Optind 1 )) do?

Thus shift $((OPTIND-1)) removes all the options that have been parsed by getopts from the parameters list, and so after that point, $1 will refer to the first non-option argument passed to the script.

How getopts work in Unix?

Description. The getopts command is a Korn/POSIX Shell built-in command that retrieves options and option-arguments from a list of parameters. An option begins with a + (plus sign) or a - (minus sign) followed by a character. An option that does not begin with either a + or a - ends the OptionString.


1 Answers

According to man getopts, OPTIND is the index of the next argument to be processed (starting index is 1). Hence,

In sh foo.sh -abc CCC Blank arg1 is -abc, so after a we are still parsing arg1 when next is b (a 1). Same is true when next is c, we are still in arg1 (b 1). When we are at c, since c needs an argument (CCC) the OPTIND is 3 (arg2 is CCC and we skip it).

In sh foo.sh -a -b -c CCC Blank, arg1 is a, arg2 is b, arg3 is c, and arg4 is CCC. So we get a 2, b 3, c 5.

In sh foo.sh -ab -c CCC Blank args are (1:-ab, 2: -c, 3: CCC and 4: Blank). So we get: a 1, b 2, c 4.

In sh foo.sh -a -bc CCC Blank args are (1: -a, 2: -bc, 3: CCC, 4: Blank) and we get a 2, b 2, c 4.

like image 192
perreal Avatar answered Oct 23 '22 02:10

perreal