使用getopts运行脚本是第一次运行,但第二次运行它时不起作用[重复]

问题描述 投票:2回答:1

这个问题在这里已有答案:

这是我的剧本。我从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$ 

我已经梳理了互联网,无法找到任何有关此行为的解释。

bash shell command-line-arguments getopts
1个回答
4
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.