%60%20%E4%BD%9C%E4%B8%BA%E6%9C%80%E5%90%8E%E4%B8%80%E4%B8%AA%E6%A8%A1%E5%BC%8F%E5%AD%90%E5%8F%A5%EF%BC%8C%E6%88%96%E8%80%85%20%60%5C%3F)%60%20%E5%92%8C%20%60%3A)%60%20%E4%BD%9C%E4%B8%BA%E6%9C%80%E5%90%8E%E4%B8%A4%E4%B8%AA%E6%A8%A1%E5%BC%8F%E5%AD%90%E5%8F%A5%EF%BC%9F.png)
使用getopts
withcase
子句时,*)
作为最后一个模式子句的模式子句是否相当于作为最后两个模式子句的\?)
and模式子句的并集?:)
具体来说,
while getopts "<optionString>" opt; do
case $opt in
a) a="$OPTARG"
;;
b) b="$OPTARG"
;;
...
;;
\?) printf "illegal option: -%s\n" "$OPTARG" >&2
exit 1
;;
:) printf "missing argument for -%s\n" "$OPTARG" >&2
exit 1
;;
esac
done
和
while getopts "<optionString>" opt; do
case $opt in
a) a="$OPTARG"
;;
b) b="$OPTARG"
;;
...
;;
*) printf "illegal option: -%s, or missing argument for -%s\n" "$OPTARG" "$OPTARG" >&2
exit 1
;;
esac
done
谢谢。
答案1
如果您使用静默错误报告(当 the 的第一个字符是冒号时),您只需要真正检查:
和?
。getopts
bash
optstring
当getopts
不以这种方式使用时,它将针对无效选项和缺少选项参数生成自己的诊断消息(这些通常已经足够了)。事实上,除非它被静音,否则它不会放置:
或?
在变量中。
在 case 语句中使用*
是捕获这两种情况的一种方法,但如果getopts
被静音,您将不知道触发了哪个错误,而只能向an error occurred while parsing the command line options
用户说一些话。