How to terminate a Batch File if it is in the middle of an IF command block?
I have recently discovered that if I press ctrl+C to cancel a running timeout command that is placed within an IF command block, then rather than being immediately presented with the "terminate batch job" choice, instead the timeout command will cancel and the rest of the commands in the IF block will execute. Only once all commands within the block are finished will I finally be given the "terminate batch job" prompt.
Is there any known way to force ctrl+C to bring up the terminate prompt instantly in these circumstances? Typically I press ctrl+C to cancel precisely because I don't want any further code to be executed.
Or is there any other instant terminate keys (aside from alt+F4)?
See the following code if you are unsure what I am talking about. If you try to ctrl+C terminate during the first timeout then the timeout will cancel straightaway, then the next echo and then timeout will begin, and only once both are finished will you finally be given the option to terminate the script.
@echo off
if exist C:\ (
echo press ctrl+C to cancel the following 30s timeout
timeout /nobreak 30
echo instead of seeing a terminate batch job prompt straight away, you will see this message
echo in 5s the terminate batch job option will appear
timeout /nobreak 5
)
echo just a dummy line for the above demonstration to remain onscreen before the console closes
While not a direct answer, there is a work-around you can use: the CALL :label
and EXIT /B
statements. For example:
@echo off
if exist C:\ CALL :InIF
echo just a dummy line for the above demonstration to remain onscreen before the console closes
GOTO :EOF
:InIF
echo press ctrl+C to cancel the following 30s timeout
timeout /nobreak 10
echo instead of seeing a terminate batch job prompt straight away, you will see this message
echo in 5s the terminate batch job option will appear
timeout /nobreak 5
EXIT /B
:EOF
This technique essentially mimics a sub-routine call, and will honor a standard Ctrl+C
(or Ctrl+Break
) key press, as you might expect.