【问题标题】:Windows Batch Script: why is the syntax of this IF command incorrect?Windows 批处理脚本:为什么这个 IF 命令的语法不正确?
【发布时间】:2019-11-05 21:27:26
【问题描述】:

说明

如果文件 init.marker 比文件 setup.pysetup.cfg 更新,则尝试使用 Windows 批处理脚本 (where the code below comes from) 将 Init has already been made 打印到屏幕上:

FOR /F %%i IN ('DIR /B /O:D init.marker setup.py setup.cfg') DO SET last_modified_file=%%i
IF "%last_modified_file%"=="init.marker"(
    ECHO Init has already been made
)

我遇到了The syntax of the command is incorrect. 错误。


错误从何而来

假设我们将上述批处理脚本写入了一个名为make_init.cmd 的文件,该文件与文件init.markersetup.pysetup.cfg 位于同一目录中。 (我们可以使用批处理脚本创建这些文件,参见 [1]。查看this answer 了解有关如何使用批处理脚本创建空文件的更多信息。)让我们使用 cmd.exe 运行它,它会为我们提供以下输出:

User> make_init.cmd
User> FOR /F %i IN ('DIR /B /O:D init.marker setup.py setup.cfg') DO SET last_modified_file=%i
User> SET last_modified_file=init.marker
User> SET last_modified_file=setup.py
User> SET last_modified_file=setup.cfg
The syntax of the command is incorrect.
User> IF "setup.cfg"=="init.marker" (

让我们首先通过运行相同的脚本但将 IF 语句换成简单的 ECHO 语句来看看我们的 FOR 语句是否按预期工作。 (见[2])
输出是我们所期望的:

User> make_init.cmd
User> COPY /B NUL  1>init.marker
User> COPY /B NUL  1>setup.py
User> COPY /B NUL  1>setup.cfg
User> FOR /F %i IN ('DIR /B /O:D init.marker setup.py setup.cfg') DO SET last_modified_file=%i
User> SET last_modified_file=init.marker
User> SET last_modified_file=setup.py
User> SET last_modified_file=setup.cfg
User> ECHO setup.cfg
setup.cfg

据我了解,这意味着上述不正确的命令必须是
IF "%last_modified_file%"=="init.marker" (,其计算结果为IF "setup.cfg"=="init.marker" (

那么,为什么在任何其他情况下(参见 [3])这样的 IF 语句是完全有效的?


问题

上述 IF 命令的语法有什么问题?


附件

[1] 用于创建所需文件的脚本扩展。

COPY /B NUL > init.marker
COPY /B NUL > setup.py
COPY /B NUL > setup.cfg
FOR /F %%i IN ('DIR /B /O:D init.marker setup.py setup.cfg') DO SET last_modified_file=%%i
IF "%last_modified_file%"=="init.marker"(
    ECHO Init has already been made
)

[2] 用 ECHO 语句替换 IF 语句

COPY /B NUL > init.marker
COPY /B NUL > setup.py
COPY /B NUL > setup.cfg
FOR /F %%i IN ('DIR /B /O:D init.marker setup.py setup.cfg') DO SET last_modified_file=%%i
ECHO %last_modified_file%

[3] IF 语句的简单测试脚本

:: Filename:        test_if.cmd
:: How to execute:  test_if.cmd hello

IF "%1"=="hello" (
    SET the_greeting_message=Greetings, traveller.
)
IF "%the_greeting_message%"=="Greetings, traveller." (
    ECHO %the_greeting_message%
)

【问题讨论】:

  • if 命令行的( 字符之前插入一个空格。
  • @Bill_Stewart 哇,这让我感到失望和尴尬 ^^。你修好了,非常感谢!你能发布一个答案让我接受吗?
  • 移除了不适用的bash标签。

标签: batch-file cmd windows-10


【解决方案1】:

问题是您在if 命令行上的尾随( 字符之前缺少一个空格:

IF "%last_modified_file%"=="init.marker"(

在结尾的 ( 字符之前插入一个空格,它应该可以正确解析。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-19
    • 2013-07-11
    • 2016-02-24
    • 1970-01-01
    • 2014-11-21
    • 2021-04-27
    • 1970-01-01
    相关资源
    最近更新 更多