bash 脚本中的 Getopt 解析错误(选项声明错误)
Getopt parsing error in bash script (option declaration mistake)
我需要在 bash 脚本中获得 4 个选项(每个选项都有一个短版本和一个长版本)。
这是我所做的:
OPTS=`getopt -l :author,icon,channel,message: -o :aicm: -- "$@"` ||
exit 1
eval set -- "$OPTS"
while true; do
case "" in
-a|--author) echo "A:''"; shift;;
-i|--icon) echo "I:''"; shift 2;;
-m|--message) echo "M:''"; shift 2;;
-c|--channel) echo "C:''"; shift 2;;
--) shift; break;;
*) echo Error; exit 1;;
esac
done
这是我得到的:
命令
docker run --rm -e SLACK_TOKEN slacker notify --channel foo
产出
C:'--'
Error
当然,我想要这样的输出:
C:'foo'
您的 getopt
命令看起来有点古怪。您似乎使用 :
作为某种分隔符,在这里:
-l :author,icon,channel,message:
这里:
-o :aicm:
这没有任何意义。 :
在选项定义中有特殊含义;查看 getopt(1)
手册页:
-l, --longoptions longopts
The long (multi-character) options to be recognized. More than one
option name may be specified at once, by separating the names
with commas. This option may be given more than once, the longopts
are cumulative. Each long option name in longopts may be followed
by one colon to indicate it has a required argument, and by two colons
to indicate it has an optional argument.
空头期权也是如此。
所以假设你所有的选项都有参数,你会写:
OPTS=`getopt -l author:,icon:,channel:,message: -o a:i:c:m: -- "$@"` ||
我需要在 bash 脚本中获得 4 个选项(每个选项都有一个短版本和一个长版本)。
这是我所做的:
OPTS=`getopt -l :author,icon,channel,message: -o :aicm: -- "$@"` ||
exit 1
eval set -- "$OPTS"
while true; do
case "" in
-a|--author) echo "A:''"; shift;;
-i|--icon) echo "I:''"; shift 2;;
-m|--message) echo "M:''"; shift 2;;
-c|--channel) echo "C:''"; shift 2;;
--) shift; break;;
*) echo Error; exit 1;;
esac
done
这是我得到的:
命令
docker run --rm -e SLACK_TOKEN slacker notify --channel foo
产出
C:'--'
Error
当然,我想要这样的输出:
C:'foo'
您的 getopt
命令看起来有点古怪。您似乎使用 :
作为某种分隔符,在这里:
-l :author,icon,channel,message:
这里:
-o :aicm:
这没有任何意义。 :
在选项定义中有特殊含义;查看 getopt(1)
手册页:
-l, --longoptions longopts
The long (multi-character) options to be recognized. More than one option name may be specified at once, by separating the names with commas. This option may be given more than once, the longopts are cumulative. Each long option name in longopts may be followed by one colon to indicate it has a required argument, and by two colons to indicate it has an optional argument.
空头期权也是如此。
所以假设你所有的选项都有参数,你会写:
OPTS=`getopt -l author:,icon:,channel:,message: -o a:i:c:m: -- "$@"` ||