Can I have an IF block in DOS batch file?

前端 未结 5 2124
梦谈多话
梦谈多话 2020-12-05 03:41

In a DOS batch file we can only have 1 line if statement body? I think I found somewhere that I could use () for an if block just like the {} used

5条回答
  •  抹茶落季
    2020-12-05 04:13

    Logically, Cody's answer should work. However I don't think the command prompt handles a code block logically. For the life of me I can't get that to work properly with any more than a single command within the block. In my case, extensive testing revealed that all of the commands within the block are being cached, and executed simultaneously at the end of the block. This of course doesn't yield the expected results. Here is an oversimplified example:

    if %ERRORLEVEL%==0 (
    set var1=blue
    set var2=cheese
    set var3=%var1%_%var2%
    )
    

    This should provide var3 with the following value:

    blue_cheese
    

    but instead yields:

    _
    

    because all 3 commands are cached and executed simultaneously upon exiting the code block.

    I was able to overcome this problem by re-writing the if block to only execute one command - goto - and adding a few labels. Its clunky, and I don't much like it, but at least it works.

    if %ERRORLEVEL%==0 goto :error0
    goto :endif
    
    :error0
    set var1=blue
    set var2=cheese
    set var3=%var1%_%var2%
    
    :endif
    

提交回复
热议问题