Link to home
Start Free TrialLog in
Avatar of brianadkins
brianadkinsFlag for United States of America

asked on

Gracefully exit a looping batch file


What are some good methods for allowing users to gracefully exit a looping batch file?

=================
:loop
rem allow graceful exit here
goto :loop
=================


I've tried using CHOICE to allow users to hit a specific key to get out, but it appears that the choice command stagnates (hangs) if the command window of the batch file looses focus:
=================
:loop
echo hit 'Q' to exit this utility or 'Y' to manually refresh
choice /N /Ty,2 /Cqy
if %ERRORLEVEL%==1 goto :EOF
goto :loop
:EOF
exit
=================


I've also tried just telling user to hit Ctrl-C, but then they get the annoying "Terminate Batch Job Y/N" question:
=================
:loop
echo hit 'Ctrl-C' to exit this utility
sleep 3
goto :loop
=================


Any better ideas?

Thanks,
-Brian




Avatar of SteveGTR
SteveGTR
Flag of United States of America image

You could put a time restraint on the choice command like so:

choice /CYN /TN,01 Press 'Y' to exit loop

if ERRORLEVEL 2 goto LOOP

This will give the user a 1 second window to abort during processing.

Other than that, I'd just have the user press CTRL-C and confirm with the Y/N prompt.

Good Luck,
Steve
There's always the pause statment:

echo Press any key to exit this program . . .
pause>nul
Avatar of brianadkins

ASKER

Thanks for the ideas so far, but:

SteveGTR - that is essentially what I have above (just a one second wait instead of two)

InteractiveMind - Pause certainly is graceful, but it prevents the looping I'm after.

-Brian
ASKER CERTIFIED SOLUTION
Avatar of SteveGTR
SteveGTR
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks for the help...  I have no understanding of assembly code, but your method was functional.  Turns out I almost had a seizure from the flashing command windows opening and closing... : )

I'll probably just end up going with option A which was Press Ctrl-C to exit ... and deal with the "Terminate batch Job" question as needed.

Thanks for the suggestions guys...

-Brian