Nested IF ( IF ( ... ) ELSE( .. ) ) statement in batch

Viewed 69472

I'm trying to write an IF ELSE statement nested inside another IF statement. Here's what I have:

IF %dirdive%==1 ( 
    IF DEFINED log (
        ECHO %DATE%, %TIME% >> %log%
        FOR /R %root1% %%G IN (.) DO (
            SET _G=%%G
            CALL :TESTEVERYTHING !_G:~0,-1! %root1% %root2% %log%
        )
        GOTO :end
    ) ELSE ( 
        ECHO %DATE%, %TIME%
        FOR /R %root1% %%G IN (.) DO (
            SET _G=%%G
            CALL :TESTEVERYTHINGnolog !_G:~0,-1! %root1% %root2%
        )
        GOTO :end
    )
)

When log isn't defined, I get:

The syntax of the command is incorrect.
ECHO Wed 07/18/2012, 15:50:12.34 >>

Aaaand I'm at a loss. I've tried playing with the parenthesis. I've moved the last ) up onto the same line as the one before it and it doesn't work. The thing is, it works fine when log is defined. It seems to break right after or at IF %dirdive%==1, as it won't get to an echo command inserted right after that.

5 Answers

Another solution is to use GOTO. Maybe not so elegant, but easy to understand.

IF %dirdive%==1 ( 
    IF DEFINED log GOTO logdefined ELSE GOTO nolog
)

:logdefined
ECHO %DATE%, %TIME% >> %log%
FOR /R %root1% %%G IN (.) DO (
    SET _G=%%G
    CALL :TESTEVERYTHING !_G:~0,-1! %root1% %root2% %log%
)
GOTO :end

:nolog
ECHO %DATE%, %TIME%
FOR /R %root1% %%G IN (.) DO (
    SET _G=%%G
    CALL :TESTEVERYTHINGnolog !_G:~0,-1! %root1% %root2%
)
GOTO :end
Related