简体   繁体   中英

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

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

Kindly explain.

You've put a ":" after the "b" in getopts line. 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 ":".

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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