Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse command line arguments with SWITCH in BATCH file

We are trying to make a switch statement which is parsing command line argument in a batch file.

mybatch.bat -a 10 -b name -c India --zipcode 20

Only -a, -b, -c are parsing parameter (which is starts with -).

Our code will be like:

for %%x in (%*) do (
     switch(%%x) (
          case a:
                 SET first_number=%arg%
                 break
          case b:
                 SET name=%arg%
          case c:
                 for %%x in (%*) do (
                       SET place =%place% %arg%
                  )
          default:
                  echo wrong parameter
           )
like image 864
Abhi Kumar Sahu Avatar asked Sep 21 '25 02:09

Abhi Kumar Sahu


1 Answers

The Batch file below parses all arguments that start with - and creates a series of variables that start with "option" and the names and values of all options given:

@echo off
setlocal EnableDelayedExpansion

set "option="
for %%a in (%*) do (
   if not defined option (
      set arg=%%a
      if "!arg:~0,1!" equ "-" set "option=!arg!"
   ) else (
      set "option!option!=%%a"
      set "option="
   )
)

SET option

For example:

>test -a 10 -b name -c India --zipcode 20
option--zipcode=20
option-a=10
option-b=name
option-c=India

This way, you need to make no changes in the parsing code if you want to add/change/delete any option, just use the value of the option you want. For example:

if defined option-x (
   echo Option -x given: "%option-x%"
) else (
   echo Option -x not given
)
like image 177
Aacini Avatar answered Sep 22 '25 23:09

Aacini