【问题标题】:Running a script with getopts works the first time, but doesn't work the second time I run it [duplicate]使用 getopts 运行脚本第一次有效,但第二次运行时无效[重复]
【发布时间】:2018-07-12 01:28:33
【问题描述】:

这是我的脚本。我从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来运行脚本?
  • @choroba 有什么不同?

标签: bash shell command-line-arguments getopts


【解决方案1】:

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

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

【讨论】:

  • 啊,有道理。谢谢。
猜你喜欢
  • 2019-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-16
  • 1970-01-01
  • 2019-04-13
  • 1970-01-01
  • 2019-10-29
相关资源
最近更新 更多