[英]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.