批量处理我的IF语句有问题

时间:2015-03-17 17:03:10

标签: batch-file cmd

这是我之后的简化版本:

SET outFile=
IF "%outFile%"=="" (
    echo Output file=[Console]
    SET outFile=CON
) ELSE ( 
    IF "%outFile:~0,3%"=="%HOMEDRIVE%\" (
        echo Output file=%outFile%
        SET outFile=%outFile%
    ) ELSE ( 
        echo Output file=%cd%\%outFile%
        SET outFile=%cd%\%outFile%  
    )
)

它适用于所有条件,除了outFile为空,返回错误"(此时出乎意料。"

1 个答案:

答案 0 :(得分:0)

在批处理中添加setlocal enabledelayedexpansion,并在第二个IF中使用!outFile:~0,3!,如下所示:

setlocal enabledelayedexpansion

IF "%outFile%"=="" (
    echo Output file=[Console]
    SET outFile=CON
) ELSE ( 
    IF "!outFile:~0,3!"=="%HOMEDRIVE%\" (
        echo Output file=%outFile%
        SET outFile=%outFile%
    ) ELSE ( 
        echo Output file=%cd%\%outFile%
        SET outFile=%cd%\%outFile%  
    )
)

此外,您可以查看此主题以获取有关What is the proper way to test if variable is empty in a batch file?

的更多信息