[英]For two consecutive options, `getopts` taking the second option as the argument of first
[英]How to not allow the user to specify two options at once in getopts?
在getopts中,用戶可以指定我們在代碼中引入的所有選項。 輸入以下腳本。
while getopts d:s o
do case "$o" in
d) seplist="$OPTARG";;
s) paste=hpaste;;
[?]) print >&2 "Usage: $0 [-s] [-d seplist] file ..."
exit 1;;
esac
done
不應允許用戶同時指定選項-d和-s。 即。
當用戶同時使用-d和-s選項運行腳本時,他應該收到錯誤消息,不能同時指定-d和-s。
天真的實現是維持$OPTION_COUNT
:
OPTION_COUNT=0
while getopts d:s o
do case "$o" in
d) seplist="$OPTARG"; (( OPTION_COUNT ++ );;
s) paste=hpaste; (( OPTION_COUNT ++ );;
[?]) print >&2 "Usage: $0 [-s] [-d seplist] file ..."
exit 1;;
esac
done
if [ "$OPTION_COUNT" -gt 1 ]; then echo "too many options"; fi
您應該檢查傳遞給腳本的特定選項。 維護起來會容易得多。
#!/usr/bin/env bash
d_option=0
s_option=0
while getopts d:s o
do case "$o" in
d)
seplist="$OPTARG"
d_option=1
;;
s)
paste=hpaste
s_option=1
;;
[?]) print >&2 "Usage: $0 [-s] [-d seplist] file ..."
exit 1;;
esac
done
if [ "x$d_option" == "x1" ] && [ "x$s_option" == "x1" ]; then
echo "both options specified."
exit 1
fi
您應該檢查其他選擇的提示。
while getopts d:s o
do case "$o" in
d) if [ -z "$paste" ]; then
seplist="$OPTARG"
else
print >&2 "Option -s is already specified"
exit 1
fi
;;
s) if [ -z "$seplist" ]; then
paste=hpaste
else
print >&2 "Option -d is already specified"
exit 1
fi
;;
[?]) print >&2 "Usage: $0 {-s | -d seplist} file ..."
exit 1;;
esac
done
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.