我希望getopts能够识别用户何时传递"-?“和"-h”,并发送到我的帮助函数。如果出现无效选项,我也不希望getopts将用户发送到帮助函数。我希望显示一个不同的消息,告诉他们这是一个无效的选项,并发送到stderr。
这是我的选择部分:
options(){
# grab options flags before entering application:
while getopts ":h?vu:d" opts; do
case "${opts}"
in
h\?) # Help
help_section
exit 0
;;
v) # Version
version
exit 0
;;
u) # units
other_units="$OPTARG"
;;
d) # Debug
debug=1
;;
\?) # Invalid options
echo "no here"
>&2 echo "[!] ERROR: Invalid Option: -$OPTARG"
exit 1
;;
esac
done
shift $((OPTIND -1))
# Run main function
main_run "$@"
}问题:当用户输入无效选项时,getopts一直向用户发送帮助。我需要确保用户识别他们提供了一个无效的参数;我不想将他们发送到帮助。
有办法用getopts实现这一点吗?或者在getopts之外构建逻辑来捕获和执行我需要的东西?
发布于 2022-04-01 22:18:27
Bash命令行输入示例
下面的示例演示如何接受各种类型的输入,并默认为无效的输入选项。
# -- Get input options (if any)
function get_user_input_options() {
if [[ $# -lt 1 ]];then
echo "no input, help infomration"
#show_help_info_function
exit
fi
while [[ $# > 0 ]] ;do
key="$1"
case ${key,,} in
-o|--opt)
echo " we a seting option=$2"
option=2
shift
;;
-\?|-h|--\?|--help)
echo "help information"
#show_help_info_function # a function that prints help and exits
exit;
;;
*)
echo "not understanding your input at all!"
exit;
;;
esac
shift
done
}
get_user_input_options "$@"这是怎么回事?
我们读取所有的输入,并根据类型,我们可以转移到下一个或移动两次。如果你看到更多关于你的问题,我们接受-?还是.?如果发生这种情况,它将执行帮助部分中的操作;如果没有处理这些输入,它将执行“*”部分中默认的任何操作,这意味着任何输入。注意:这只是一个例子,在本例中,“帮助”部分会导致脚本停止,即使提供了其他输入,这也可能是您个人想要做的。
示例输出
$ ./args.sh -o something
we a seting option=something
$ ./args.sh -j somethingelse
not understading your input at all!
$ ./args.sh -?
help information
$ ./args.sh
no input, help infomration
$ ./args.sh -h
help informationhttps://stackoverflow.com/questions/71712779
复制相似问题