【问题标题】:How to pass in shell scripts mandatory and optional flags in command line using getopts?如何使用 getopts 在命令行中传入 shell 脚本强制和可选标志?
【发布时间】:2017-01-05 16:53:03
【问题描述】:

我想通过 getopts 将 3 个参数传递给我的 shell 脚本。该脚本至少需要前2个,第三个参数是可选的。如果未设置,则使用其默认值。这样以下都可以工作:

sh script.sh -a "/home/dir" -b 3
sh script.sh -a "/home/dir" -b 3 -c "String"

我尝试像下面那样做,但它总是忽略我输入的参数。

usage() {
 echo "Usage: Script -a <homedir> -b <threads> -c <string>"
  echo "options:"
                echo "-h      show brief help"

  1>&2; exit 1;
}

string="bla"

while getopts h?d:t:a: args; do
case $args in
    -h|\?)
        usage;
        exit;;
    -a ) homedir=d;;
    -b ) threads=${OPTARG};;
    -c ) string=${OPTARG}
        ((string=="bla" || string=="blubb")) || usage;;
    : )
        echo "Missing option argument for -$OPTARG" >&2; exit 1;;
    *  )
        echo "Unimplemented option: -$OPTARG" >&2; exit 1;;
  esac
done

我是这个 getopts 的新手,在我只是按特定顺序添加参数之前,我不想在这里做。我在这里阅读了很多问题,但不幸的是没有找到我需要的方式。

我真的很想在这里得到您的帮助。谢谢:)

【问题讨论】:

  • 您是否查看过 while 循环中 $args 的值? getops tutorial 有一些很好的信息;也许你应该先检查那里。

标签: shell command-line-arguments getopts


【解决方案1】:

您的脚本中有几个错误。最重要的是,$args 仅包含选项的字母,没有前导破折号。此外,您提供给 getopts 的选项字符串 (h?d:t:a:) 不适合您实际处理的选项 (h?abc)。这是循环的更正版本:

while getopts "h?c:b:a:" args; do
case $args in
    h|\?)
        usage;
        exit;;
    a ) homedir=d;;
    b ) threads=${OPTARG};;
    c ) string=${OPTARG}
        echo "Entered string: $string"
        [[ $string=="bla" || $string=="blubb" ]] && usage;;
    : )
        echo "Missing option argument for -$OPTARG" >&2; exit 1;;
    *  )
        echo "Unimplemented option: -$OPTARG" >&2; exit 1;;
  esac
done

【讨论】:

  • 非常感谢
  • 如果它解决了您的问题,您可以考虑将答案标记为“正确”。
猜你喜欢
  • 2021-07-29
  • 2019-02-04
  • 2016-09-24
  • 1970-01-01
  • 2012-07-24
  • 1970-01-01
  • 2011-07-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多