Search code examples
batch-fileswitch-statement

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
           )

Solution

  • Normally you try to keep things simple and have a set order for the parameters. To handle parameters in any, random order is a lot more effort than just knowing that %1 = number, %2 = name and %3 onwards = place.

    That said, here's an attempt at a solution. I'm ignoring --params in the place section, just joining the values together.

    @echo off
    setlocal
    
    :loop
    if x%1 equ x goto done
    set param=%1
    if %param:~0,1% equ - goto checkParam
    :paramError
    echo Parameter error: %1 
    
    :next
    shift /1
    goto loop
    
    :checkParam
    if "%1" equ "-a" goto A
    if "%1" equ "-b" goto B
    if "%1" equ "-c" goto C
    goto paramError
    
    :A
        shift /1
        set first_number=%1
        goto next
    
    :B
        shift /1
        set name=%1
        goto next
    
    :C
        set place=
    :GetPlaces
        shift /1
        set param=%1
        if not defined param goto donePlaces
        if %param:~0,2% equ -- (
            shift /1
            goto processPlace
        )
        if %param:~0,1% equ - goto donePlaces
    :processPlace
    echo.%place%
        if x%1 neq x (
            set place=%place% %1
            goto GetPlaces
        )
    :donePlaces
        rem remove leading space
        if defined place set place=%place:~1%
        goto loop
    
    
    
    :done
    
    echo num=%first_number%     name=%name%     place=%place%