bash getopts具有多个和强制性选项

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

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

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

您可以连接您提供的选项,并且getopts将分隔它们。在您的案例陈述中,您将单独处理每个选项。

您可以在看到选项时设置标志,并检查以确保在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

shift $(($OPTIND - 1))

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

这表示getopts函数的完整参考实现,但只是较大脚本的草图。

相关文章

用的openwrt路由器,家里宽带申请了动态公网ip,为了方便把2...
#!/bin/bashcommand1&command2&wait从Shell脚本并行...
1.先查出MAMP下面集成的PHP版本cd/Applications/MAMP/bin/ph...
1、先输入locale-a,查看一下现在已安装的语言2、若不存在如...
BashPerlTclsyntaxdiff1.进制数表示Languagebinaryoctalhexa...
正常安装了k8s后,使用kubect工具后接的命令不能直接tab补全...