关于这类事情有许多问题,但让我们假设我们的目标是安装了getopt和getopts的通用Linux系统(我们不会使用它们,但它们似乎很受欢迎)
如何同时解析长参数(--example | --example simple-option)和短参数(-e | -esimple-example | -e simple-example)
发布于 2010-04-15 15:47:16
您希望将getopt与long和short选项一起使用。一个来自工作代码的示例:
# Parse arguments
TEMP=$(getopt -n $PROGRAM_NAME -o p:P:cCkhnvVS \
--long domain-password:,pop3-password:\
,create,cron,kill,help,no-sync-passwords,version,verbose,skip-pop3 \
-- "$@")
# Die if they fat finger arguments, this program will be run as root
[ $? = 0 ] || die "Error parsing arguments. Try $PROGRAM_NAME --help"
eval set -- "$TEMP"
while true; do
case $1 in
-c|--create)
MODE="CREATE"; shift; continue
;;
-C|--cron)
MODE="CRON"; shift; continue
;;
-k|--kill)
MODE="KILL"; shift; continue
;;
-h|--help)
usage
exit 0
;;
-n|--no-sync-passwords)
SYNC_VHOST=0; shift; continue
;;
-p|--domain-password)
DOMAIN_PASS="$2"; shift; shift; continue
;;
-P|--pop3-password)
POP3_PASS="$2"; shift; shift; continue
;;
-v|--version)
printf "%s, version %s\n" "$PROGRAM_NAME" "$PROGRAM_VERSION"
exit 0
;;
-v|--verbose)
VERBOSE=1; shift; continue
;;
-S|--skip-pop3)
SKIP_POP=1; shift; continue
;;
--)
# no more arguments to parse
break
;;
*)
printf "Unknown option %s\n" "$1"
exit 1
;;
esac
done 请注意,die是一个先前定义的函数(未显示)。
-n选项告诉getopt以我的程序名报告错误,而不是以getopt名。-o定义一个短选项列表(选项后的:表示需要的参数),--long指定长选项列表(对应于短选项)。
其余的只是一个简单的开关,适当地调用shift来推进参数指针。注意,调用shift; shift;只是一个顽固的习惯。在当前的现代世界中,shift 2可能就足够了。
现代的getopt在较新的平台上非常一致,但是在较旧的(大约在Redhat 9之前)系统上可能会遇到一些可移植性问题。有关向后兼容性的信息,请参阅man getopt。但是,您不太可能遇到需要它的情况。
最后,在解析选项之后,您可以再次调用:
eval set -- "$@"这会将参数指针移动到getopt解析选项后留在命令行上的任何其他内容。然后你可以通过shift来继续阅读它们。例如,如果命令看起来像这样:
./foo --option bar file1.txt file2.txt file3.txt完成后,不要忘了创建一个方便的-h / --help选项来打印新的漂亮选项。:)如果您使输出help2man友好,那么您的新工具就会有一个即时的手册页。
编辑
在大多数发行版上,您可以在/usr/share/doc/util-linux/examples中找到更多示例getopt代码,默认情况下应该已经安装了这些代码。
https://stackoverflow.com/questions/2642707
复制相似问题