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
exitThe 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.
12 Answers
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
exitIf 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
) 2 What am I missing here?
The == comparison operator always results in a string comparison.
You need to use EQU instead to perform a numerical comparison.
Use the following batch file:
@echo off
IF NOT %1% EQU 0 ( goto proc3
)
IF %2% EQU 0 ( goto proc1
)
goto proc2
:proc1
echo in Proc1 0 0
pause
goto :exit
:proc2
echo in Proc2 0 N0
pause
goto :exit
:proc3
echo in Proc3 N0 0
pause
:exitNotes:
- Some
goto :exitss have been added to terminate the procs instead ofexitwhich terminates the enclosingcmdshell.
Example output:
F:\test>example 0 0
in Proc1 0 0
Press any key to continue . . .
F:\test>example 0 1
in Proc2 0 N0
Press any key to continue . . .
F:\test>example 1 0
in Proc3 N0 0
Press any key to continue . . .
F:\test>Further Reading
- An A-Z Index of the Windows CMD command line - An excellent reference for all things Windows cmd line related.
- if - Conditionally perform a command.