簡體   English   中英

對於兩個連續的選項,`getopts`將第二個選項作為第一個參數

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

我有一個代碼:

    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"

簡單的代碼,只是為了了解getopts命令的行為。 當我像這樣運行腳本時:

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

它會將選項-b的參數設為-f 而我要打印:

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

代碼到底在哪里出錯? 同樣對於選項-b-e如果沒有參數,我也要打印:

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

請解釋。

您已在getopts行中的“ b”之后放置了“:”。 那告訴它以后期望爭論。 如果您不希望將下一個參數視為-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