【问题标题】:Batch SET /A in for loop breaks loop variablesfor 循环中的批处理 SET /A 中断循环变量
【发布时间】:2016-04-09 12:04:42
【问题描述】:

我有这个批处理脚本,它应该枚举目录中的所有文件:

SETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
SET /A cn=0
SET cwd=%~dp0

ECHO Files:
FOR %%I IN (%cwd%\*) DO (
    SET /A cn=cn+1
    ECHO !cn!
    IF "%%I"=="buthow" ()
    ECHO %%~nxI
)
EXIT /B 0

假设我们在文件夹中有文档d1.txtd2.txtd3.txt。上面的代码按预期工作,但是当我删除什么都不做的 if 语句(?)时,我得到以下输出:

1
d1.txt
2
cnd2.txt
3
cnd3.txt

这是为什么呢?

【问题讨论】:

  • 代码有两个 ECHO命令:ECHO !cn!应该显示cn变量的值,ECHO %%~nxI应该显示每个命令的名称和扩展名文件,因此您显示的输出证明代码“按预期工作”(没有奇怪的if 命令)。
  • 你还能再马虎点吗!?发布的代码“按预期工作”?!?!我认为不会,因为您的 IF 语句存在致命的语法错误。但是没有 IF 的输出完全是应该的。
  • 没有。预期的输出应该是 d2.txt 而不是 cnd2.txt

标签: batch-file for-loop set


【解决方案1】:

阅读if /?

Performs conditional processing in batch programs.

IF [NOT] ERRORLEVEL number command
IF [NOT] string1==string2 command
IF [NOT] EXIST filename command

  NOT               Specifies that Windows should carry out
                    the command only if the condition is false.

  ERRORLEVEL number Specifies a true condition if the last program run
                    returned an exit code equal to or greater than the number
                    specified.

  string1==string2  Specifies a true condition if the specified text strings
                    match.

  EXIST filename    Specifies a true condition if the specified filename
                    exists.

  command           Specifies the command to carry out if the condition is
                    met.  Command can be followed by ELSE command which
                    will execute the command after the ELSE keyword if the
                    specified condition is FALSE

The ELSE clause must occur on the same line as the command after the IF.

请注意,() 不是有效命令:

==> if 1==2 ()
) was unexpected at this time.

==> if 1==1 ()
) was unexpected at this time.

==> ()
) was unexpected at this time.

==>

【讨论】:

  • 可能是 WINE 对它的解释有点不同,我无法在 Windows 上进行测试,但是当我用 ECHO 或 PAUSE 语句填充它时,输出没有(意外的)差异。问题是文件名开头的额外cns 来自哪里?
  • 请在FOR %%I … 行之前添加ECHO ON;联系 WINE 的Bugzilla Bug Tracker。请使用edit 链接在您的问题中添加wine 标签。然而,(echo(>NUL) 语句将 什么都不做 而不是语法错误()
猜你喜欢
  • 2013-08-08
  • 1970-01-01
  • 2016-04-14
  • 1970-01-01
  • 1970-01-01
  • 2019-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多