小编Mom*_*ina的帖子

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

我想通过 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 …
Run Code Online (Sandbox Code Playgroud)

shell getopts command-line-arguments

2
推荐指数
1
解决办法
5220
查看次数

标签 统计

command-line-arguments ×1

getopts ×1

shell ×1