简体   繁体   English

对于两个连续的选项,`getopts`将第二个选项作为第一个参数

[英]For two consecutive options, `getopts` taking the second option as the argument of first

I have a code: 我有一个代码:

    while getopts ab:cde:f opt
    do
        case ${opt} in
            b|e)
                [[ ${OPTARG} = -* ]]   && usage "Invalid parameter \"${OPTARG}\" provided for agurment \"-        ${opt}!\""
                [[ ${#OPTARG} -eq 0 ]] && usage "Argument \"-${opt}\" requires a parameter!${OPTARG}"
            ;;
        esac

        case $opt in
            a) minusa=$opt;;
            b) minusb=$opt
            file_b=$OPTARG;;
            c) minusc=$opt;;
            d) minusd=$opt;;
            e) minuse=$opt
            file_e=$OPTARG;;
            f) minusf=$opt;;
            /?) echo Unrecognized parameter
             exit 1;;
        esac

    done
    echo  "minusa:$minusa","minusb:$minusb","file_b:$file_b","minusc:$minusc","minusd:$minusd","minuse:$minuse","file_e:$file_e","minusf:$minusf"

Simple code, just to understand the behavior of getopts command. 简单的代码,只是为了了解getopts命令的行为。 When I run the script like: 当我像这样运行脚本时:

    ./eg2 -b -f
    ./eg2: line 7: usage: command not found
    minusa:,minusb:b,file_b:-f,minusc:,minusd:,minuse:,file_e:,minusf:

It is taking the argument for option -b as -f . 它会将选项-b的参数设为-f Whereas I want to print: 而我要打印:

     [[ ${OPTARG} = -* ]]   && usage "Invalid parameter \"${OPTARG}\" provided for agurment \"-${opt}!\""

Where exactly in the code I'm going wrong? 代码到底在哪里出错? Also for the options -b and -e if there is no arguments , I want to print: 同样对于选项-b-e如果没有参数,我也要打印:

    [[ ${#OPTARG} -eq 0 ]] && usage "Argument \"-${opt}\" requires a parameter!${OPTARG}"

Kindly explain. 请解释。

You've put a ":" after the "b" in getopts line. 您已在getopts行中的“ b”之后放置了“:”。 That tells it to expect an argument afterwards. 那告诉它以后期望争论。 If you don't want the next argument to be treated like an argument to -b , remove that ":". 如果您不希望将下一个参数视为-b的参数,请删除该“:”。

[[ "${OPTARG}" =~ "^-[az]" ]] && echo "Invalid parameter \\"${OPTARG}\\" provided for agurment \\"-${opt}!\\""解决了该问题。 ..谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM