2012-09-12 151 views
0
while getopts ":hufc:p:i" opt; do 

    case $opt in 
    h) 
     usage 
     exit 1 
     ;; 
    u) 
     DOUPDATE=false 
     ;; 
    f) 
     DOCONFIRMATION=false 
     ;; 
    c) 
     CUSTOMERTYPE=$OPTARG 
     ;; 
    p) 
     CUSTOMERPROFILE=$OPTARG 
     ;; 
    i) 
     echo "LOL $INSTALL" 
     INSTALL=true 
     ;; 
    \?) 
     echo "Invalid option: -$OPTARG" >&2 
     exit 1 
     ;; 
    :) 
     echo "Option -$OPTARG requires an argument." >&2 
     exit 1 
     ;; 
    esac 
done 

上面是我的bash代碼。當我嘗試在命令行中使用「i」作爲參數時,不會輸入案例i。Bash getopts無法識別參數

我該怎麼辦?

+1

適合我。將這個確切的代碼複製到'foo.sh'中,然後運行'sh foo.sh -i'並打印'LOL'。 – Thomas

+1

這應該工作,你用'-i'嗎?或者只是'i',就像這樣:'./myScript i'?你必須像這樣使用'-i':'./myScript -i'。 – pb2q

+0

我不明白,因爲在我的終端中同樣使用-i或者我不打印「LOOL」。 – Kefka

回答

0

如果你的命令行在我之前有任何無效的選項,它不會解析任何比錯誤更​​遠的選項。如果你的命令行有一個沒有後續參數的-c或-p進入CustomerType或CustomerProfile,它不會解析任何更遠的參數。

#Examples that should work 
script.sh -i 
script.sh -c customerX -p profileX -i 
script.sh -iz 

#Examples that will not work 
script.sh -hi #-h option will exit before it parses -i 
script.sh -zi #invalid option z will exit 
script.sh -c customerX -p -i #Missing required argument after -p