batch script: why if and else batch run after if condition failed?

I recommend you to have this habit of using :

  • The %userprofile% environment variable instead of c:\users\%username%\*\...
  • Further Reading How to open your user profile folder in Windows
  • Adding double quotes to this variable "%tempfile%" since your file contains spaces.

So your code can be written like this :


@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