getopts&防止意外将简短的选项解释为参数

发布于 2025-01-28 10:28:06 字数 641 浏览 3 评论 0原文

这是一个玩具示例,说明我的意思是:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

方觉久 2025-02-04 10:28:06

这就是我想到的。它似乎有效,但我想是可以简化正则是。我想我忽略了一些优势案例。

validOpts="sf:e:"
optsWithArgs=$(echo "$validOpts" | grep -o .: | tr -d ':\n')

# ensure that options that require (or have optional) arguments are not combined with other short options
invalidOptArgFormats=( "[^$optsWithArgs[:space:]]+[$optsWithArgs]" "[$optsWithArgs]([^ =]|[ =]$|$)" )
IFS="|" && invalidOptArgRegEx="-(${invalidOptArgFormats[*]})"
[[ "$@" =~ $invalidOptArgRegEx ]] && echo -e "An option you provided takes an argument; it is required to have its option\n    on a separate - to prevent accidentally passing an opt as an argument.\n    (You provided ${BASH_REMATCH[0]})" && exit 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.

validOpts="sf:e:"
optsWithArgs=$(echo "$validOpts" | grep -o .: | tr -d ':\n')

# ensure that options that require (or have optional) arguments are not combined with other short options
invalidOptArgFormats=( "[^$optsWithArgs[:space:]]+[$optsWithArgs]" "[$optsWithArgs]([^ =]|[ =]$|$)" )
IFS="|" && invalidOptArgRegEx="-(${invalidOptArgFormats[*]})"
[[ "$@" =~ $invalidOptArgRegEx ]] && echo -e "An option you provided takes an argument; it is required to have its option\n    on a separate - to prevent accidentally passing an opt as an argument.\n    (You provided ${BASH_REMATCH[0]})" && exit 1
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文