Sho*_*e X 4 bash shell getopts command-line-arguments
这是我的脚本。我根据本教程对其进行了改编,因此它不会是脚本本身的错误。(原始脚本也有同样的问题。)
#!/bin/bash
while getopts "a:" opt; do
case $opt in
a)
echo "-a was triggered, Parameter: $OPTARG"
;;
esac
done
Run Code Online (Sandbox Code Playgroud)
这是我的输出:
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$
Run Code Online (Sandbox Code Playgroud)
我已经梳理了互联网,找不到对这种行为的任何解释。
source在当前 shell 的执行上下文中运行指定文件中的 bash 命令。该执行上下文包括变量OPTIND,其getopts使用记“当前”参数索引。因此,当您重复source执行脚本时,每次调用都getopts从上次调用处理的最后一个参数之后的参数索引处开始。
OPTIND在脚本开始时重置为 1 或使用bash getopt.sh. (通常getopts作为通过 she-bang 执行运行的脚本的一部分调用,因此它有自己的执行上下文,您不必担心它的变量。)