bash OPTIND 变量如何在 shell 内置 getopts 中工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14249931/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 04:13:21  来源:igfitidea点击:

How does the OPTIND variable work in the shell builtin getopts

bashshellgetopts

提问by Blank

My shell script is quite simple, as the following:

我的 shell 脚本非常简单,如下所示:

  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 OPTINDworks with different command line invocation, I am confused by the output.

我无法理解如何OPTIND使用不同的命令行调用,我对输出感到困惑。

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

你能帮忙弄清楚计算的机制OPTIND吗?

回答by perreal

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

根据man getopts,OPTIND是要处理的下一个参数的索引(起始索引为 1)。因此,

In sh foo.sh -abc CCC Blankarg1 is -abc, so after awe 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 cneeds an argument (CCC) the OPTINDis 3(arg2 is CCC and we skip it).

sh foo.sh -abc CCC Blankarg1 中是-abc,所以在a接下来是b( a 1)时我们仍在解析 arg1 。当 next is 时也是如此c,我们仍然在 arg1 ( b 1) 中。当我们在 时c,因为c需要一个参数 ( CCC),所以OPTIND3(arg2 是 CCC,我们跳过它)。

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.

在 中sh foo.sh -a -b -c CCC Blank, arg1 是a, arg2 是b, arg3 是c, arg4 是CCC。所以我们得到a 2, b 3, c 5.

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

sh foo.sh -ab -c CCC Blank参数中有 (1: -ab, 2: -c, 3:CCC和 4: Blank)。所以我们得到:a 1, b 2, c 4

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

sh foo.sh -a -bc CCC Blankargs 中有 (1: -a, 2: -bc, 3: CCC, 4: Blank) 我们得到a 2, b 2, c 4.