运行 带有 getopts 的脚本第一次工作,但第二次不工作我 运行

Running a script with getopts works the first time, but doesn't work the second time I run it

这是我的脚本。我从 this tutorial 改编而来,所以它不会是脚本本身的错误。 (原来的脚本也有同样的问题。)

#!/bin/bash

while getopts "a:" opt; do
  case $opt in
    a)
      echo "-a was triggered, Parameter: $OPTARG"
      ;;
  esac
done

这是我的输出:

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 命令。该执行上下文包括变量 OPTINDgetopts 使用它来记住 "current" 参数索引。因此,当您重复 source 脚本时,getopts 的每次调用都从上一次调用处理的最后一个参数之后的参数索引开始。

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