Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows Bat file optional argument parsing

Tags:

batch-file

I need my bat file to accept multiple optional named arguments.

mycmd.bat man1 man2 -username alice -otheroption 

For example my command has 2 mandatory parameters, and two optional parameters (-username) that has an argument value of alice, and -otheroption:

I'd like to be able to pluck these values into variables.

Just putting out a call to anyone that has already solved this. Man these bat files are a pain.

like image 554
chickeninabiscuit Avatar asked Oct 20 '10 00:10

chickeninabiscuit


People also ask

What is %% in a BAT file?

Use double percent signs ( %% ) to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c. ( <set> ) Required. Specifies one or more files, directories, or text strings, or a range of values on which to run the command.

How do I pass a command line argument to a batch file?

Batch parameters (Command line parameters): In the batch script, you can get the value of any argument using a % followed by its numerical position on the command line. The first item passed is always %1 the second item is always %2 and so on. If you require all arguments, then you can simply use %* in a batch script.

How do I pass a command line argument in Windows?

For example, entering C:\abc.exe /W /F on a command line would run a program called abc.exe and pass two command line arguments to it: /W and /F. The abc.exe program would see those arguments and handle them internally.

Does BAT file work on Windows 10?

On Windows 10, a batch file typically has a ". bat" extension, and it is a special text file that contains one or multiple commands that run in sequence to perform various actions with Command Prompt.


1 Answers

Though I tend to agree with @AlekDavis' comment, there are nonetheless several ways to do this in the NT shell.

The approach I would take advantage of the SHIFT command and IF conditional branching, something like this...

@ECHO OFF  SET man1=%1 SET man2=%2 SHIFT & SHIFT  :loop IF NOT "%1"=="" (     IF "%1"=="-username" (         SET user=%2         SHIFT     )     IF "%1"=="-otheroption" (         SET other=%2         SHIFT     )     SHIFT     GOTO :loop )  ECHO Man1 = %man1% ECHO Man2 = %man2% ECHO Username = %user% ECHO Other option = %other%  REM ...do stuff here...  :theend 
like image 154
ewall Avatar answered Sep 19 '22 14:09

ewall