Windows 批处理中的 if/then/else 语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11845409/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 09:46:26  来源:igfitidea点击:

if/then/else statements in Windows batch

windowsbatch-file

提问by Jeegar Patel

In a shell script I have the following code:

在shell脚本中,我有以下代码:

if echo Mr.32 ; then
  echo Success
else
  echo Failed
  exit
fi

What is the equivalent syntax for Windows batch files?

Windows 批处理文件的等效语法是什么?

回答by dbenham

I'm having a hard time envisioning when ECHO would fail with a returned ERRORLEVEL not equal 0. I suppose it could fail if the output has been redirected to a file and the target drive is full.

我很难想象 ECHO 何时会因返回的 ERRORLEVEL 不等于 0 而失败。我想如果输出已重定向到一个文件并且目标驱动器已满,它可能会失败。

CptHammer has posted a good solution using ERRORLEVEL, although it uses GOTO unnecessarily. It can be done without GOTO using:

CptHammer 使用 ERRORLEVEL 发布了一个很好的解决方案,尽管它不必要地使用了 GOTO。它可以在没有 GOTO 的情况下使用:

ECHO Mr.32
if errorlevel 1 (
  echo Failed
  exit /b
) else (
  echo Success
)

There is a simpler way to take action on SUCCESS or FAILURE of any command.

有一种更简单的方法可以对任何命令的 SUCCESS 或 FAILURE 采取行动。

command && success action || failure action

In your case

在你的情况下

ECHO Mr.32&& (
  echo Success
) || (
  echo Failed
  exit /b
)

回答by cptHammer

I think something like this might do the trick:

我认为这样的事情可能会奏效:

REM run the command
ECHO Mr.32
IF ERRORLEVEL 1 GOTO failLabel

:successLabel
REM put code to execute in case of success here.
ECHO Success
GOTO endLabel

:failLabel
REM put code here that should be executed in case of failure.
ECHO Failed

:endLabel

This assumes the command you want to test (here: echo MR.32) returns 0 on success and anything higher on failure (BEWARE : Echo in most windows OS will return nothing and therefore, the actual value that is tested in this script is probably the return code from the last command executed just before the script. you're probably better of testing with the command : " DIR someFile.txt" that will return 0 if somefile.txt exists and 1 otherwise.)

这假设您要测试的命令(此处:echo MR.32)在成功时返回 0,在失败时返回任何更高的值(注意:大多数 Windows 操作系统中的 Echo 将不返回任何内容,因此,在此脚本中测试的实际值可能是在脚本之前执行的最后一个命令的返回代码。您可能最好使用以下命令进行测试:“DIR someFile.txt”,如果 somefile.txt 存在,则返回 0,否则返回 1。)

It is true as dbenham pointed out, that this structure uses lot of GOTO. This is because this GOTO structure is the only one that will be understood fine in all windows versions. More compact versions appeared with time but they will only work on recent windows versions.

正如 dbenham 指出的那样,这个结构使用了很多 GOTO。这是因为这个 GOTO 结构是唯一一种在所有 Windows 版本中都能很好理解的结构。随着时间的推移出现了更紧凑的版本,但它们仅适用于最近的 Windows 版本。