在 Windows 批处理文件中寻找 Unix 风格的“getopt”命令行解析

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3494898/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 15:03:01  来源:igfitidea点击:

Looking for Unix style 'getopt' command line parsing in a Windows batch file

windowsparsingbatch-filecommand-linecmd

提问by Michael Campbell

Can anyone help me find something to parse command line args in a Windows batch file like one would do in a Unix shell script using getopt/getopts? It doesn't have to be all Posix-y; just something that I can specify what switches I expect, which of them require/allow an argument. They don't need to be "long" switches; single characters will work.

谁能帮我找到一些东西来解析 Windows 批处理文件中的命令行参数,就像使用 getopt/getopts 在 Unix shell 脚本中所做的那样?不一定都是 Posix-y;只是我可以指定我期望的开关,其中哪些需要/允许参数。它们不需要是“长”开关;单个字符将起作用。

It can be an external .exe that the batch file calls. It has to be freely distributable.

它可以是批处理文件调用的外部 .exe。它必须可以自由分发。

回答by Kris

You can you something like this (-h has no args, hence no shift after that, -b and -s take additional args, so shift them).

你可以做这样的事情(-h 没有 args,因此之后没有移位,-b 和 -s 需要额外的 args,所以移动它们)。

:GETOPTS
 if /I "%1" == "-h" goto Help
 if /I "%1" == "-b" set BASE=%2 & shift
 if /I "%1" == "-s" set SQL=%2 & shift
 shift
if not "%1" == "" goto GETOPTS

回答by Kurt Pfeifle

There is no such thing as getopt/getopts-like parsing of commandline arguments as you know from Unix/Linux.

正如您从 Unix/Linux 所知,没有像 getopt/getopts 这样的命令行参数解析。

Batch files only know about %0, %1, %2, ... and %*(and such variations as %~0, %~1... which remove quotes, should there be ones around an arg).

批处理文件只知道%0, %1, %2, ... and %*(以及诸如%~0, %~1... 之类的变体 ,它们会删除引号,如果 arg 周围有引号的话)。

Up to nine arguments. If there are more to process, you can use shift(equiv. to shift /1if enableextensionshappened) to remove the first arg and shift the rest.

最多九个参数。如果还有更多要处理的,您可以使用shift(相当于shift /1如果enableextensions发生)删除第一个 arg 并移动其余部分。

Basically that's it.

基本上就是这样。



(Maybe you should explain more what exactly you are trying to achieve with the batch, why you must use batch, and what your other external constraints are.)

(也许您应该更多地解释一下您想要通过批处理实现什么,为什么必须使用批处理,以及您的其他外部约束是什么。)