如何使用 getopts 在命令行中传递 shell 脚本的强制和可选标志?

Mom*_*ina 2 shell getopts command-line-arguments

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

sh script.sh -a "/home/dir" -b 3
sh script.sh -a "/home/dir" -b 3 -c "String"
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

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

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

Geo*_* P. 7

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

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
Run Code Online (Sandbox Code Playgroud)