批处理文件:两个连续的 IF [英] Batch file: Two consecutive IFs

查看:57
本文介绍了批处理文件:两个连续的 IF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试理解批处理文件中 IF 的语法.

I'm trying to understand the syntax of IF in batch files.

鉴于此代码(有效):

CHOICE /C YN /M "Do it?"
IF ERRORLEVEL == 2 GOTO skip
IF ERRORLEVEL == 1 GOTO doIt
GOTO end

:doIt
echo Do it!
GOTO end

:skip
echo Abort!
GOTO end

:end

为什么我不能改变两个 IF 的顺序?如果我一开始写 IF ERRORLEVEL == 1 GOTO doIt,我会得到错误的行为.现在 Do it 每次都会执行,不管输入如何.

Why can't I change the order of the two IF's? If I would write IF ERRORLEVEL == 1 GOTO doIt at first, I get wrong behavior. Now Do it gets executed every time, regardless of the input.

推荐答案

if 命令支持一些特殊的(不区分大小写的)关键字:

The if command supports a few special (case-insensitive) keywords:

  • exist(检查文件是否存在)
  • defined(检查环境变量)
  • ErrorLevel(检查最后一个错误)
  • CmdExtVersion(检查命令扩展)
  • exist (to check for file existence)
  • defined (to check for environment variable)
  • ErrorLevel (to check for the last error)
  • CmdExtVersion (to check for command extensions)

如果在 ifif/Iif notif/I not代码>,进入特殊的比较模式.如果这些关键字都不存在,则期望对两个值进行正常比较(使用比较运算符 == 强制进行字符串比较,或使用 equ 之一>neqgtrgeqlssleq 用于尝试将两个值解释为整数并按原样比较它们,或者,如果不可能,则将它们作为字符串进行比较).

If any of those is encountered immediately behind if, if /I, if not or if /I not, special comparison modes are entered. If none of these keywords is present, a normal comparison of two values is expected (using the comparison operator == to force string comparison, or using one of equ, neq, gtr, geq, lss, leq for trying to interpret both values as integers and comparing them as such, or, if not possible, comparing them as strings).

由于您在 if 命令后紧跟声明了关键字 errorlevel,因此需要一个数字值.根据 本节1,多个连续的分隔符合并为一个.

Since you have stated the keyword errorlevel immediately following the if command, a numeric value is expected. The equal-to sign is no longer treated particularly, rather is it just regarded as a standard token delimiter just like a SPACE, according to this section1, and multiple consecutive delimiters are collapsed into one.

因此,你的命令行 if errorlevel == # 等价于 if errorlevel #,意思是 if ErrorLevel 大于或等于 #.因此,您不能交换两个 if 命令行,因为 2errorLevel 值也将满足针对 值的所述条件>1.

Therefore, your command line if errorlevel == # is equivalent to if errorlevel #, meaning if ErrorLevel is greater than or equal to #. For that reason, you cannot exchange the two if command lines, because an errorLevel value of 2 would also fulfil said condition against the value 1.

这篇关于批处理文件:两个连续的 IF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆