且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我可以在 DOS 批处理文件中有一个 IF 块吗?

更新时间:2021-09-10 10:07:41

您确实可以放置创建语句块以在条件之后执行.但是你的语法错误.括号必须完全按照所示使用:

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 <statement> (
    do something
) else (
    do something else
)

但是,我不认为 else-if 语句有任何内置语法.不幸的是,您将需要创建 if 语句的嵌套块来处理它.

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.


其次,%GPMANAGER_FOUND% == true 测试在我看来非常可疑.我不知道环境变量设置为什么或您如何设置它,但我非常怀疑您显示的代码是否会产生您正在寻找的结果.


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:

  • 在条件语句的结尾和左括号之间添加的空格.
  • 我正在设置 @echo off 以防止在执行时看到打印到控制台的所有语句,而是只看到那些特别开始的语句的输出带有 echo.
  • 我使用内置的 ERRORLEVEL 变量作为测试.阅读更多此处
  • 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