[英]How to not allow the user to specify two options at once in getopts?
In getopts user can specify all the options that we introduce in the code. 在getopts中,用户可以指定我们在代码中引入的所有选项。 Give the following script.
输入以下脚本。
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
The user should not be allowed to specify both option -d and -s. 不应允许用户同时指定选项-d和-s。 ie.
即。
When the user runs above script with both options -d and -s, he should receive an error cannot specify both -d and -s. 当用户同时使用-d和-s选项运行脚本时,他应该收到错误消息,不能同时指定-d和-s。
A naive implementation would be to maintain an $OPTION_COUNT
: 天真的实现是维持
$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
You should check for particular options passed into the script. 您应该检查传递给脚本的特定选项。 It will be much easier to maintain it.
维护起来会容易得多。
#!/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
You should check for hints of other option. 您应该检查其他选择的提示。
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.