Windows批处理脚本:为什么此IF命令的语法不正确?

说明

如果尝试使用Windows批处理脚本({{3},如果文件Init has already been made比文件init.markersetup.py较新,则将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
)

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


错误来自哪里

假设我们将上述批处理脚本写入了名为make_init.cmd的文件,该文件与文件init.markersetup.pysetup.cfg位于同一目录中。 (我们可以使用批处理脚本创建这些文件,请参见[1]。有关如何使用批处理脚本创建空文件的更多信息,请参见where the code below comes from。)让我们使用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%
)
pieric 回答:Windows批处理脚本:为什么此IF命令的语法不正确?

问题在于,(命令行上的结尾if字符之前缺少空格:

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

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

本文链接:https://www.f2er.com/3156313.html

大家都在问