Can I have an IF block in DOS batch file?

前端 未结 5 2145
梦谈多话
梦谈多话 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:08

    You can indeed place create a block of statements to execute after a conditional. But you have the syntax wrong. The parentheses must be used exactly as shown:

    if  (
        do something
    ) else (
        do something else
    )
    

    However, I do not believe that there is any built-in syntax for else-if statements. You will unfortunately need to create nested blocks of if statements to handle that.


    Secondly, that %GPMANAGER_FOUND% == true test looks mighty suspicious to me. I don't know what the environment variable is set to or how you're setting it, but I very much doubt that the code you've shown will produce the result you're looking for.


    The following sample code works fine for me:

    @echo off
    
    if ERRORLEVEL == 0 (
        echo GP Manager is up
        goto Continue7
    )
    echo GP Manager is down
    :Continue7
    

    Please note a few specific details about my sample code:

    • The space added between the end of the conditional statement, and the opening parenthesis.
    • I am setting @echo off to keep from seeing all of the statements printed to the console as they execute, and instead just see the output of those that specifically begin with echo.
    • I'm using the built-in ERRORLEVEL variable just as a test. Read more here

提交回复
热议问题