批处理脚本:为什么在 if 条件失败后 if 和 else 批处理会运行?

批处理脚本:为什么在 if 条件失败后 if 和 else 批处理会运行?

1


@echo off
set tempfile=C:\Users\*\Desktop\test case\temp\tempfile.txt
if not exist %tempfile% (
    echo if branch
    echo %TIME%
    type nul>%tempfile%
) else ( 
    echo else branch
    echo %TIME%
    echo file has already exist!
    echo =============%DATE% %TIME%==========>>%tempfile%
    echo 123>>%tempfile%
)

答案1

我建议你养成以下习惯:

因此你的代码可以这样写:


@echo off
set tempfile=%userprofile%\Desktop\test case\temp\tempfile.txt

if not exist "%tempfile%" (
    echo if branch
    echo %TIME%
    type nul>"%tempfile%"
) else ( 
    echo else branch
    echo %TIME%
    echo file has already exist!
    echo =============%DATE% %TIME%==========>>"%tempfile%"
    echo 123>>"%tempfile%"
)
pause>nul

相关内容