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

前端 未结 5 1153
春和景丽
春和景丽 2021-02-18 23:13

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

IF %dirdive%==1 ( 
    IF DEFINED lo         


        
5条回答
  •  忘掉有多难
    2021-02-19 00:05

    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.

提交回复
热议问题