bash 使用 --getopts 来获取整个单词的标志

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22025793/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 09:41:53  来源:igfitidea点击:

Using --getopts to pick up whole word flags

bashunixgetopts

提问by kid_x

Can getopts be used to pick up whole-word flags?

可以使用 getopts 来获取全字标志吗?

Something as follows:

如下:

while getopts ":abc --word" opt; do
    case ${opt} in
        a) SOMETHING
            ;;
        ...
        --word) echo "Do something else."
            ;;
    esac
done

Trying to pick up those double-dash flags.

试图拿起那些双破折号标志。

采纳答案by kid_x

Found one way to do this:

找到了一种方法来做到这一点:

while getopts ":abc-:" opt; do
    case ${opt} in
        a) echo "Do something"
            ;;
        ...
        -)
            case ${OPTARG} in
                "word"*) echo "This works"
                    ;;
            esac
    esac
done

By adding -: to the opstring and adding a sub-case using $OPTARG, you can pick up the long option you want. If you want to include an argument for that option, you can add * or =* to the case and pick up the argument.

通过将 -: 添加到操作字符串并使用 $OPTARG 添加子案例,您可以选择所需的长选项。如果您想为该选项包含一个参数,您可以在案例中添加 * 或 =* 并选择该参数。

回答by Keenan

Basically Ark's answer but easier and quicker to read than the mywiki page:

基本上是 Ark 的答案,但比 mywiki 页面更容易、更快地阅读:

#!/bin/bash
# example_args.sh

while [ $# -gt 0 ] ; do
  case  in
    -s | --state) S="" ;;
    -u | --user) U="" ;;
    -a | --aarg) A="" ;;
    -b | --barg) B="" ;;

  esac
  shift
done

echo $S $U, $A $B

#$is the number of arguments, -gtis "greater than", $1is the flag in this case, and $2is the flag's value.

#$是参数的数量,-gt是“大于”,$1在这种情况下$2是标志,是标志的值。

./example_args.sh --state IAM --user Yeezy -a Do --barg itresults in:

./example_args.sh --state IAM --user Yeezy -a Do --barg it结果是:

IAM Yeezy, Do it