我正在寻找一个可重用的代码片段,它为bash执行命令行参数验证.
理想情况下类似于Apache Commons CLI提供的功能:
Commons CLI支持不同类型的选项:
它会自动为程序生成"使用"消息,如下所示:
usage: ls
-A,--almost-all do not list implied . and ..
-a,--all do not hide entries starting with .
-B,--ignore-backups do not list implied entried ending with ~
-b,--escape print octal escapes for nongraphic characters
--block-size <SIZE> use SIZE-byte blocks
-c with -lt: sort by, and show, ctime (time of last
modification of file status information) with
-l:show ctime and sort by name otherwise: sort
by ctime
-C list entries by columns
Run Code Online (Sandbox Code Playgroud)
我会在我的Bash脚本开头包含此代码段,并在脚本中重复使用它.
必须有这样的东西.我不相信我们都在编写这种效果或类似的代码:
#!/bin/bash
NUMBER_OF_REQUIRED_COMMAND_LINE_ARGUMENTS=3
number_of_supplied_command_line_arguments=$#
function show_command_usage() {
echo usage:
(...)
}
if (( number_of_supplied_command_line_arguments < NUMBER_OF_REQUIRED_COMMAND_LINE_ARGUMENTS )); then
show_command_usage
exit
fi
...
Run Code Online (Sandbox Code Playgroud)
这是我使用的解决方案(在网上找到它,可能在这里,不记得肯定).请注意,GNU getopt(/usr/bin/getopt)确实支持ant -projecthelp使用该选项的单个破折号长选项(样式)-a,但是我没有使用它,所以它没有在示例中显示.
此代码解析3个选项:--host value或-h value,--port value或-p value和.--table value或-t value.如果未设置所需参数,则对其进行测试
# Get and parse options using /usr/bin/getopt
OPTIONS=$(getopt -o h:p:t: --long host:,port:,table: -n "$0" -- "$@")
# Note the quotes around `$OPTIONS': they are essential for handling spaces in
# option values!
eval set -- "$OPTIONS"
while true ; do
case "$1" in
-h|--host) HOST=$2 ; shift 2 ;;
-t|--table)TABLE=$2 ; shift 2 ;;
-p|--port)
case "$2" in
"") PORT=1313; shift 2 ;;
*) PORT=$2; shift 2 ;;
esac;;
--) shift ; break ;;
*) echo "Internal error!" ; exit 1 ;;
esac
done
if [[ -z "$HOST" ]] || [[-z "$TABLE" ]] || [[ -z "$PORT" ]] ; then
usage()
exit
if
Run Code Online (Sandbox Code Playgroud)
使用getoptsshell内置的替代实现(这仅支持小选项):
while getopts ":h:p:t:" option; do
case "$option" in
h) HOST=$OPTARG ;;
p) PORT=$OPTARG ;;
t) TABLE=$OPTARG ;;
*) usage(); exit 1 ;;
esac
done
if [[ -z "$HOST" ]] || [[-z "$TABLE" ]] || [[ -z "$PORT" ]] ; then
usage()
exit
if
shift $((OPTIND - 1))
Run Code Online (Sandbox Code Playgroud)
进一步阅读GNU getopt和getopts bash内置