How the OPTIND variable works in the getopts shell

My shell script is pretty simple:

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

And I am testing 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 can not understand how OPTIND works with various command line calls, the output is confusing to me.

Can you help figure out the mechanism for calculating OPTIND ?

+6
source share
1 answer

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

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

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

In sh foo.sh -ab -c CCC Blank arguments 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: (1: -a , 2: -bc , 3: CCC , 4: Blank ) and we get a 2, b 2, c 4 .

+11
source

All Articles