I'm developing a complex, long-running batch script, and came upon a little issue when debugging. I have a command-line window open to the root path of the script, so I can type myscript.bat
to fire it off for testing. I am using PAUSE
commands between statements to watch the behavior of the script. However, I discovered that typing CTRL+C during a PAUSE
command to cancel execution is simply interpreted as a key to continue execution, rather than breaking the script as intended.
I know I can simply kill/close the command window, but it's a little annoying to navigate back to the correct path in a new command-window every time. Is there a way to properly break a batch script's execution easily while it is currently in a PAUSE
?
Edit: It looks like PAUSE
works fine in simple scripts, as indicated by @dbenham. However, if you have multiple PAUSE
statements nested inside of a FOR
iteration, then you can't break in the middle of the FOR
iteration – only at the end. Here is a sample script that demonstrates the issue:
@echo off
for /l %%y in (2008, 1, 2013) do (
echo 1
pause
echo 2
pause
echo 3
pause
echo 4
pause
echo 5
pause
)
If you try to terminate any of the first four PAUSE
statements, you will find that your terminate command is ignored and execution continues anyway. But once you reach the end, to the fifth PAUSE
, you do get the terminate prompt (in the example output below, I was pressing CTRL+C at every prompt):
Z:\>test
1
Press any key to continue . . .
2
Press any key to continue . . .
3
Press any key to continue . . .
4
Press any key to continue . . .
5
Press any key to continue . . .
Terminate batch job (Y/N)? y
Any ideas how to prevent this behavior?
Best Answer
It works fine for me on Win 7 (32 bit)
Here is a trivial test script
When I run the above without pressing
<Ctrl-C>
, I get the following:When I press
<Ctrl-C>
at the "Press any key" prompt, I get:EDIT: Solution to follow-up question
It doesn't need to be in a loop. The problem exists with any parenthesized block of code. The entire block is parsed in one pass and then executed from memory.
I don't think there is a fix using the PAUSE command. But I have a simple solution that should give the debug functionality you want. Just make sure that the PAUSE environment variable is not already defined before you run your script.