Nesting IF in Windows Bat file

I am having some difficulty in understanding how the Nested IF works in windows .bat script. What I wish to achieve is as follows. I shall be passing two parameters to a bat file

IF first parameter = 0 AND if Second parameter = 0 run proc1

IF first parameter = 0 AND Second not 0 run proc2

IF first parameter is not 0 run proc 3

The skeleton of the code I have written so far is

@echo off

IF %1% == 0 (
    IF %2% == 0 ( goto proc1
    ) ELSE ( goto proc2
)
  ELSE ( goto proc3
)

:proc1
echo in Proc1 0 0
pause
exit
:proc2
echo in Proc2 0 N0
pause
exit
:proc3
echo in Proc3 N0  0
pause
exit

The issue is that it’s working fine for the first two conditions but when first parameter is non zero is still falls thru proc1 whereas expected is proc3. What am I missing here? The script does not give any error except if the parameters are omitted in the first place.


Solution 1:

I'm not actually sure you need ELSE, let alone a nested IF, for your use case:

@echo off

IF NOT "%1%"=="0" (
    goto proc3
)
IF "%2%"=="0" ( 
    goto proc1
) 

goto proc2 

:proc1
echo in Proc1 0 0
pause
exit
:proc2
echo in Proc2 0 N0
pause
exit
:proc3
echo in Proc3 N0  0
pause
exit

If for some reason you really do want to nest your IFs, you're missing a bracket:

Your batch:

IF %1% == 0 (
    IF %2% == 0 ( goto proc1
    ) ELSE ( goto proc2
)
***MISSING )***  ELSE ( goto proc3
)

Batch that should work:

IF "%1%" == "0" (
    IF "%2%" == "0" ( 
    goto proc1
    ) ELSE ( 
    goto proc2
    )
) ELSE ( 
    goto proc3
)