5

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.

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

1

2 Answers 2

16

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

: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
Sign up to request clarification or add additional context in comments.

1 Comment

it's worth adding here that /I enables case insensitive comparisons - thus both -S and -s would enable the SQL line - and may not be desirable for all cases.
1

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

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).

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

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.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.