getopts&防止意外将简短的选项解释为参数
这是一个玩具示例,说明我的意思是:
while getopts "sf:e:" opt; foundOpts="${foundOpts}${opt}" ; done
echo $foundOpts
问题是getopts
在参数方面并不特别聪明。例如,./ myscript.sh -ssssf
将输出选项需要一个参数 - f
。那挺好的。
但是,如果某人误认为./ myscript.sh -ssfss
,它会解析喜欢-ss -s -f ss
,这不是可取的行为!
如何检测到这一点?理想情况下,我想强迫要分别定义的f
参数,并允许-f foo
或-f = foo
,但不是-sf = foo
或-sf foo
。
这可能不做毛茸茸的事情吗?我想我可以用匹配$@
对- [^ef [:space:]]*[ef] {ef] {1} [=]来做一些事情。 (。*)
,但我担心误报(那条正则是不完全正确的),
谢谢!
Here's a toy example that shows what I mean:
while getopts "sf:e:" opt; foundOpts="${foundOpts}${opt}" ; done
echo $foundOpts
problem is that getopts
isn't particularly smart when it comes to arguments. for example, ./myscript.sh -ssssf
will output option requires an argument -- f
. That's good.
But if someone does ./myscript.sh -ssfss
by mistake, it parses that like -ss -f ss
, which is NOT desirable behavior!
How can I detect this? Ideally, I'd like to force that f
parameter to be defined separately, and allow -f foo
or -f=foo
, but not -sf=foo
or -sf foo
.
Is this possible without doing something hairy? I imagine I could do something with a RegEx, along the lines of match $@
against something like -[^ef[:space:]]*[ef]{1}[ =](.*)
, but I'm worried about false positives (that regex might not be exactly right)
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这就是我想到的。它似乎有效,但我想是可以简化正则是。我想我忽略了一些优势案例。
Here's what I've come up with. It seems to work, but I imagine the RegEx could be simplified. And I imagine there are edge cases I've overlooked.