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

batch-file

Solution

The source of your problem is that even if a branch of an IF statement does not execute, it still must have valid syntax.

When `log` is not defined, then the following line

ECHO %DATE%, %TIME% >> %log%

expands to the following when `log` is undefined

ECHO someDate, someTime >>

There is no file name after the redirection, which results in a syntax error.

As long as your `log` variable is not already defined with enclosing quotes (when it is defined that is), then simply changing the line as follows should fix it:

ECHO %DATE%, %TIME% >> "%log%"

That line expands to the following when `log` is undefined

ECHO someDate, someTime >> ""

Which is valid syntax. It will fail with a "The system cannot find the path specified" error if it is executed, but it won't execute because log is undefined :-)

EDIT

Perhaps a better solution is to define a new variable that includes the redirection operator in the value if and only if `log` is defined. Then you don't even need your big IF statement and the code is easier to maintain.

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

Note that normal expansion `%redirect%` must be used in the ECHO statement. Delayed expansion `!redirect!` will not work because the redirection phase of the command parser occurs prior to delayed expansion.

Problem

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.

Original source