[英]Required option getopts linux
我必須編寫一個bash腳本:
schedsim.sh [-h] [-c #CPUs ] -i pathfile
h和c是可選選項。 我是必需的,當運行腳本時,如果它沒有i選項 - >錯誤消息。
如何在getopts中創建一個必需的選項? 謝謝!
另一個問題:如何為選項的參數設置默認值? 比方說,如果沒有提供c參數 - > c的參數默認值為1。
您無法進行必需的參數,因為“如果缺少該參數,則內置的getopts會返回錯誤”。
但是制作一個能夠自己完成的功能是微不足道的:
#!/bin/bash
function parseArguments () {
local b_hasA=0
local b_hasB=0
local b_hasC=0
while getopts 'a:b::c' opt "$@"; do
case $opt in
'a')
b_hasA=1
;;
'b')
b_hasB=1
;;
'c')
b_hasC=1
;;
esac
done
if [ $b_hasA -ne 0 ]; then
echo "A present"
fi
if [ $b_hasB -ne 0 ]; then
echo "B present"
fi
if [ $b_hasC -ne 0 ]; then
echo "C present"
else
echo "Error: C absent"
exit 1
fi
}
#Quotes required to avoid removing characters in $IFS from arguments
parseArguments "$@"
測試:
$ ./test.bash -c
C present
$ ./test.bash -b
./test.bash: option requires an argument -- b
Error: C absent
$ ./test.bash -b foo
B present
Error: C absent
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.