如何在 shell 中解析长格式参数?
我看到的所有内容都使用 getopt
或稍微花哨的 getopts
,它只支持单字符选项(例如 -h
但不支持 - -帮助
)。我想做一些花哨的长选择。
Everything I see uses getopt
or the slightly-fancier getopts
which only supports one-character options (e.g., -h
but not --help
). I want to do fancy long options.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我做了类似的事情这个:
正如您所看到的,这很好地支持单字符和较长的选项。它允许将值与每个参数关联,如
--configFile
的情况。它也具有相当的可扩展性,对于可以配置哪些选项等没有人为限制。如上所述,
"${1:-}"
可以防止在 bash 中运行时出现“未绑定变量”错误“严格”模式(set -euo pipelinefail
)。I've done something like this:
As you can see, this supports both the single-character and the longer options nicely. It allows for values to be associated with each argument, as in the case of
--configFile
. It's also quite extensible, with no artificial limitations as to what options can be configured, etc.As included above, the
"${1:-}"
prevents an "unbound variable" error when running in bash "strict" mode (set -euo pipefail
).假设您“想要做一些奇特的长选项”,而不管使用什么工具,只需使用
getopt
(getopts
似乎主要在可移植性至关重要时使用)。这是关于最大复杂度的示例你会得到:使用此代码,你可以指定
-e
/--exclude
多次,并且${excludes[@]}
将包含所有给定的排除项。处理后(--
始终存在),剩余的任何内容都存储在$@
中。Assuming that you "want to do fancy long options" regardless of the tool, just go with
getopt
(getopts
seems to be mainly used when portability is crucial). Here's an example of about the maximum complexity that you'll get:With this code, you can specify
-e
/--exclude
more than once, and${excludes[@]}
will contain all of the given excludes. After processing (--
is always present) anything remaining is stored in$@
.我创建了一个最容易使用且无需自定义的 bash 函数。只需使用该函数并传递所有带或不带参数的长选项,该函数会将它们设置为变量,并将相应的选项参数作为脚本中的值。
最新的原始源代码可以在这里找到:
https://github .com/theAkito/akito-libbash/blob/master/bishy.bash
I have created a bash function that is the easiest to use and needs no customization. Just use the function and pass all long options with or without arguments and the function will set them as variables with the corresponding option arguments as values in your script.
The up to date original source code is available here:
https://github.com/theAkito/akito-libbash/blob/master/bishy.bash