问题描述
我有以下代码段来解析 /bin/dash
中的短选项和长选项。
选项 -n|--dry-run
没有参数。但是 --exclude
应该采用 --exclude='foo'
形式的字符串。更复杂的是,--exclude
没有短选项。
以下代码在我使用 script.sh --exclude
时有效,但是当我使用 script.sh --exclude='foo'
时,出现错误:
option '--exclude' doesn't allow an argument
这是我的代码:
#!/bin/sh
OPTS=$(getopt --options 'n' --long 'exclude,dry-run' --name "$0" -- "$@")
if [ $? != 0 ] ; then
printf "\n\033[1;31m Error:\033[0m Failed to parse options...exiting.\n\n"
exit 1
fi
eval set -- "$OPTS"
unset OPTS
# extract options and their arguments into variables.
while true ; do
case "$1" in
--exclude )
EXCLUDE="y"
shift
;;
-n | --dry-run )
DRYRUN="y"
shift
;;
-- )
shift
break
;;
*)
printf "\n\033[1;31m Error:\033[0m Invalid option: \033[1;31m-$OPTARG\033[0m\n\n"
exit 1
;;
esac
done
echo \$\@ = $@
我需要改变什么才能使用 --exclude='foo'
?
解决方法
您需要通过在名称后附加一个 --exclude
来指定 :
可以接受一个参数。
OPTS=$(getopt --options 'n' --long 'exclude:,dry-run' --name "$0" -- "$@")
来自手册页:
-l,--longoptions longopts
要识别的长(多字符)选项。更多的 一次可以指定不止一个选项名称,通过 用逗号分隔名称。这个选项可能是 多次给出,longopts 是累积的。 每个 longopts 中的长选项名称可以后跟一个冒号 表示它有一个必需的参数, 和两个冒号 表示它有一个可选参数。