Wednesday, July 11, 2007

Never Edit A Running Batch Script

If you have a long running batch script, you should be careful to never edit and then save the newly edited file while the script is running.

Consider the following simple example.

@echo off

:START

echo hello

pause

goto START

echo oops

goto :EOF

Now run it, and while it's waiting for your input to continue, open the file again, and remove the first line, @echo off and save the file.  Now once you give your input to let it continue, instead of executing the next line after pause, which is goto START, it executes the next line after that, so you will see this output.

hello

Press any key to continue . . .

oops

The reason it skips a line is because you just deleted a line.  The batch processor executes your script line by line, and it does not load your script in memory when it starts.  Instead, it remembers which line it needs to fetch next, and when it finishes executing the current line, it reads the file again and gets that next line.  Now obviously changing the content of the script file while you are executing it will give you undesirable execution order of your script.

No comments: