庆典getopts的多和强制性选项 [英] bash getopts with multiple and mandatory options

查看:142
本文介绍了庆典getopts的多和强制性选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

时有可能使用getopts的处理多个选项在一起吗?例如,-ir的MyScript的MyScript或-irv。

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

另外,我在那里基于一个条件脚本需要强制选项的情况。例如,如果参数脚本是一个目录,我将需要指定-R或连同任何其他选项(的MyScript -IR MYDIR或-ir的MyScript或MYDIR的MyScript -i -r MYDIR或MyScript可-i -R -r选项MYDIR),在文件的情况下,只有-i就足够了(-i的MyScript MYFILE)。

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).

我试图寻找,但没有得到任何答案。

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

推荐答案

您可以连接您提供的选项和 getopts的将它们分开。在你的情况语句,您将单独处理每个选项。

You can concatenate the options you provide and getopts will separate them. In your case statement you will handle each option individually.

您可以设置一个标志,当选项被看到和检查,以确保强制的选项(!)是present的 getopts的循环完成后。

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

下面是一个例子:

#!/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

shift $(($OPTIND - 1))

if ! $rflag && [[ -d $1 ]]
then
    echo "-r or -R must be included when a directory is specified" >&2
    exit 1
fi

这再presents一个 getopts的功能的完整参考实现,而只是一个更大的脚本的草图。

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

这篇关于庆典getopts的多和强制性选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆