Search code examples
windowsbatch-filesyntax-errorbranchstatements

How to branch if-statements in batch


I've just started learning Batch, although I can't figure out the syntax for branching if-statements inside other if-statements. As in,

@echo off
set first=
set second=
set /P first=first?: %=%
if /I "%first%"=="y" (
     echo a.1
     set /P second=second?: %=%
     if /I "%second%"=="y" (
          echo b.1
     ) else if %second%=="n" (
          echo b.2
     ) else (
          echo b.3
     )
) else if /I "%first%"=="n" (
     echo a.2
) else (
     echo a.3
)
pause

Any help with that would be appreciated.


Solution

  • Your IF logic is perfectly fine. Your problem is you need delayed expansion. %second% is expanded when the statement is parsed, and the entire complex IF logic is parsed in a single pass. So %second% expands to the value that existed before the IF statement is executed, which in your case is an empty string.

    The solution is to enable delayed expansion and then use !second! to expand the value. Delayed expansion occurs after the statement is parsed.

    @echo off
    setlocal enableDelayedExpansion
    set first=
    set second=
    set /P first=first?: %=%
    if /I "%first%"=="y" (
         echo a.1
         set /P second=second?: %=%
         if /I "!second!"=="y" (
              echo b.1
         ) else if "!second!"=="n" (
              echo b.2
         ) else (
              echo b.3
         )
    ) else if /I "%first%"=="n" (
         echo a.2
    ) else (
         echo a.3
    )
    pause