`getopts` 遇到 `--` 时的行为是什么?

Tim*_*Tim 3 bash getopts

按照惯例--,这表明它之后没有更多选择。在我看来,使用getoptswithcase子句时,-)模式子句与--. 那么getopts当它遇到时的行为是什么--?它--是作为一个选项,一个非选项参数,还是两者都不是?谢谢。

Kus*_*nda 10

行为是它停止解析命令行并将其余参数保留原样。在--本身被删除(或者更确切地说,$OPTIND将表明它被处理,但$opt在下面的代码永远不会-,如果你shift "$(( OPTIND - 1 ))"作为一个通常不会,你永远不会看到它)。

例子:

#!/bin/bash

while getopts 'a:b:' opt; do
    case "$opt" in
        a)  printf 'Got a: "%s"\n' "$OPTARG" ;;
        b)  printf 'Got b: "%s"\n' "$OPTARG" ;;
        *)  echo 'error' >&2
            exit 1
    esac
done

shift "$(( OPTIND - 1 ))"

printf 'Other argument: "%s"\n' "$@"
Run Code Online (Sandbox Code Playgroud)

运行它:

$ bash script.sh -a hello -- -b world
Got a: "hello"
Other argument: "-b"
Other argument: "world"
Run Code Online (Sandbox Code Playgroud)

如您所见,-b world命令行的位没有被处理getopts.

--在第一个非选项参数处或处停止解析命令行:

$ bash script.sh something -a hello -- -b world
Other argument: "something"
Other argument: "-a"
Other argument: "hello"
Other argument: "--"
Other argument: "-b"
Other argument: "world"
Run Code Online (Sandbox Code Playgroud)

在这种情况下,没有--被“删除”,因为从来没有走那么远。getopts