Bash 第一次使用getopts运行脚本是可行的,但不会';我第二次运行它时就不工作了

Bash 第一次使用getopts运行脚本是可行的,但不会';我第二次运行它时就不工作了,bash,shell,command-line-arguments,getopts,Bash,Shell,Command Line Arguments,Getopts,这是我的剧本。我从中改编了它,所以它不会是脚本本身的错误。(原始脚本也有同样的问题。) 以下是我的输出: bash-3.2$ source getopt.sh bash-3.2$ source getopt.sh -a /dev/null -a was triggered, Parameter: /dev/null bash-3.2$ source getopt.sh -a /dev/null bash-3.2$ 我已经浏览了互联网,找不到任何关于这种行为的解释。source在当前shell

这是我的剧本。我从中改编了它,所以它不会是脚本本身的错误。(原始脚本也有同样的问题。)

以下是我的输出:

bash-3.2$ source getopt.sh
bash-3.2$ source getopt.sh -a /dev/null
-a was triggered, Parameter: /dev/null
bash-3.2$ source getopt.sh -a /dev/null
bash-3.2$ 

我已经浏览了互联网,找不到任何关于这种行为的解释。

source
在当前shell的执行上下文中运行指定文件中的bash命令。该执行上下文包括变量
OPTIND
,该变量
getopts
用于记住“当前”参数索引。因此,当您重复
source
脚本时,
getopts
的每次调用都从上一次调用处理的最后一个参数之后的参数索引开始


在脚本开头将
OPTIND
重置为1,或者使用
bash getopt.sh
调用脚本。(通常,
getopts
作为脚本的一部分被调用,脚本通过she-bang执行运行,因此它有自己的执行上下文,您不必担心它的变量。)

为什么要使用
source
来运行脚本?@choroba它有什么区别?啊,这很有意义。非常感谢。
bash-3.2$ source getopt.sh
bash-3.2$ source getopt.sh -a /dev/null
-a was triggered, Parameter: /dev/null
bash-3.2$ source getopt.sh -a /dev/null
bash-3.2$