Bash的命令行参数验证库
我正在寻找一个可重用的代码段,它为bash执行命令行参数验证 理想情况下,类似于Apache Commons CLI提供的功能: Commons CLI支持不同类型的选项:Bash的命令行参数验证库,bash,shell,Bash,Shell,我正在寻找一个可重用的代码段,它为bash执行命令行参数验证 理想情况下,类似于Apache Commons CLI提供的功能: Commons CLI支持不同类型的选项: 类似POSIX的选项(即tar-zxvf foo.tar.gz) 类似GNU的长选项(即du——人类可读——最大深度=1) 附有价值的短期期权(即gcc-O2 foo.c) 带有单连字符的长选项(即ant-projecthelp) 它会自动为程序生成一条“用法”消息,如下所示: usage: ls -A,--almo
- 类似POSIX的选项(即tar-zxvf foo.tar.gz)
- 类似GNU的长选项(即du——人类可读——最大深度=1)
- 附有价值的短期期权(即gcc-O2 foo.c)
- 带有单连字符的长选项(即ant-projecthelp)
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
用法:ls
-A、 --几乎所有人都没有列出。和。。
-a、 --所有不隐藏以开头的条目。
-B、 --忽略备份不列出以~
-b、 --转义打印非图形字符的八进制转义
--块大小使用大小字节块
-带-lt的c:按排序并显示ctime(最后一次的时间)
使用修改文件状态信息)
-l:显示ctime并按名称排序,否则:排序
按ctime
-C按列列出条目
我会在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
...
#/bin/bash
所需命令行参数的数量=3
提供的命令行参数的数量=$#
函数show_命令_用法(){
回声使用:
(...)
}
if((提供命令行参数的数量<需要命令行参数的数量));然后
显示命令的用法
出口
fi
...
这是我使用的解决方案(在网上某个地方找到的,可能就在这里,不记得了)。请注意,GNU getopt(/usr/bin/getopt
)确实支持使用选项-a
的单破折号长选项(ant-projecthelp
样式),但是我没有使用它,因此示例中没有显示它
此代码分析3个选项:--主机值
或-h值
,--端口值
或-p值
和--表值
或-t值
。如果未设置所需参数,则会对其进行测试
# 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
使用getopts
shell内置的替代实现(仅支持小选项):
进一步阅读和使用
getopts
获取简短选项。看见用Python编写脚本并使用。我怀疑答案是,由于缺乏模块基础设施,以可移植的方式加载源库的工作量与每次重写选项解析的工作量大致相同。
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))