【问题标题】:bash getopts with multiple and mandatory options具有多个强制性选项的 bash getopts
【发布时间】:2012-07-02 00:37:45
【问题描述】:

是否可以使用 getopts 一起处理多个选项?例如,myscript -iR 或 myscript -irv。

另外,我有一种情况,基于条件脚本需要强制选项。例如,如果 script 的参数是一个目录,我将需要指定 -R 或 -r 选项以及任何其他选项(myscript -iR mydir 或 myscript -ir mydir 或 myscript -i -r mydir 或 myscript -i -R mydir),如果只有文件 -i 就足够了(myscript -i myfile)。

我尝试搜索但没有得到任何答案。

【问题讨论】:

    标签: bash getopts


    【解决方案1】:

    您可以连接您提供的选项,getopts 会将它们分开。在您的case 语句中,您将单独处理每个选项。

    您可以在看到选项时设置一个标志,并检查以确保在 getopts 循环完成后出现强制“选项”(!)。

    这是一个例子:

    #!/bin/bash
    rflag=false
    small_r=false
    big_r=false
    
    usage () { echo "How to use"; }
    
    options=':ij:rRvh'
    while getopts $options option
    do
        case "$option" in
            i  ) i_func;;
            j  ) j_arg=$OPTARG;;
            r  ) rflag=true; small_r=true;;
            R  ) rflag=true; big_r=true;;
            v  ) v_func; other_func;;
            h  ) usage; exit;;
            \? ) echo "Unknown option: -$OPTARG" >&2; exit 1;;
            :  ) echo "Missing option argument for -$OPTARG" >&2; exit 1;;
            *  ) echo "Unimplemented option: -$OPTARG" >&2; exit 1;;
        esac
    done
    
    if ((OPTIND == 1))
    then
        echo "No options specified"
    fi
    
    shift $((OPTIND - 1))
    
    if (($# == 0))
    then
        echo "No positional arguments specified"
    fi
    
    if ! $rflag && [[ -d $1 ]]
    then
        echo "-r or -R must be included when a directory is specified" >&2
        exit 1
    fi
    

    这代表了getopts 函数的完整参考实现,但只是一个更大脚本的草图。

    【讨论】:

    • 非常感谢丹尼斯。我已经按照你的建议使用了这些标志。我试图通过连接选项并将它们存储在变量中来简化逻辑,然后根据提供的选项进行处理。
    • 未实现和未知选项之间的区别在于,对于前者,提供了与$options 中的选项字符匹配的选项,但在case 语句中没有条目,而对于后者,选项是提供的与 $options 中的任何字符都不匹配。
    • 请注意,您不必在算术块中为变量名称加上 $ 前缀;所以你可以做shift $((OPTIND-1))
    • 顺便说一下 * ) echo "Unimplemented option: -$OPTARG" >&2; exit 1;; 应该声明 -$option 而不是 -$OPTARG 否则它表示选项的 argument 未实现而不是 flag i> 未实现。使用-$OPTARG 的原始方式:` ./foo.bash -m foo 未实现的选项:-foo ` 如果你使用-$option,你会得到预期的结果:` ./foo -m foo 未实现的选项:-m `
    猜你喜欢
    • 2013-04-17
    • 2021-06-23
    • 2015-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-13
    • 2011-11-23
    相关资源
    最近更新 更多