简体   繁体   English

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

[英]How to pass in shell scripts mandatory and optional flags in command line using getopts?

I want to pass 3 parameters with getopts to my shell script. 我想将3个参数和getopts一起传递给我的shell脚本。 The script requires at least the first 2, the third parameter is optional. 该脚本至少需要前2个,第三个参数是可选的。 If it is not set, its default is used. 如果未设置,则使用其默认值。 So that the following would both work: 因此,以下各项将同时起作用:

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

I tried to do it like the following, but it constantly ignores my entered parameters. 我尝试按照以下方式进行操作,但是它始终忽略我输入的参数。

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

I'm new to this getopts, before I just added the parameters in a specific order, which I don't want to do here. 在刚刚按特定顺序添加参数之前,我是这个getopts的新手,我不想在这里做。 I have read a lot questions in here, but unfortenatly didn't find it the way I need it. 我在这里阅读了很多问题,但是一直以来都找不到我需要的方式。

I really would appriciate your help here. 我真的会在这里向您寻求帮助。 Thanks:) 谢谢:)

You have several mistakes in your script. 您的脚本中有几个错误。 Most importantly, $args only contains the letter of the option, without the leading dash. 最重要的是, $args仅包含选项的字母,没有前划线。 Also the option string you gave to getopts ( h?d:t:a: ) doesn't fit to the options you actually handle ( h , ? , a , b , c ). 同样,您给getopts( h?d:t:a: :)提供的选项字符串也不适合您实际处理的选项( h?abc )。 Here is a corrected version of the loop: 这是循环的更正版本:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM