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

时间:2018-02-01 16:34:04

标签: bash shell command-line-arguments getopts

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

    Collection<Event> col = 
    actions.getEvent(requestedEvents)
               .stream()
               .map(event -> new Event(event))
               .collect(
                Collectors.toMap(
                e -> e.eventType + "-" + e.productId, v -> v,
        (k1, k2) -> Long.compare(k1.eventDate.getTime(),k2.eventDate.getTime()) > 0 ? k1 : k2))
.values();

这是我的输出:

#!/bin/bash

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

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

1 个答案:

答案 0 :(得分:3)

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

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