![](/img/trans.png)
[英]The getopts command not taking in multiple options that require an argument
[英]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.