具有多个强制选项的 bash getopts

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11279423/
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-09 22:21:21  来源:igfitidea点击:

bash getopts with multiple and mandatory options

bashgetopts

提问by Ramesh Samane

Is it possible to use getopts to process multiple options together? For example, myscript -iR or myscript -irv.

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

Also, I have a situation where based on a condition script would need mandatory option. For example, if argument to script is a directory, I will need to specify -R or -r option along with any other options (myscript -iR mydir or myscript -ir mydir or myscript -i -r mydir or myscript -i -R mydir), in case of file only -i is sufficient (myscript -i myfile).

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

I tried to search but didn't get any answers.

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

回答by Paused until further notice.

You can concatenate the options you provide and getoptswill separate them. In your casestatement you will handle each option individually.

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

You can set a flag when options are seen and check to make sure mandatory "options" (!) are present after the getoptsloop has completed.

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

Here is an example:

下面是一个例子:

#!/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  ]]
then
    echo "-r or -R must be included when a directory is specified" >&2
    exit 1
fi

This represents a complete reference implementation of a getoptsfunction, but is only a sketch of a larger script.

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