Bir komutu tekrarlamak (loop)

Question

How can I loop or start a batch file over after it has completed?

Answer

Using the goto command within a batch allows a user to loop or restart a batch file after it has been completed.  Below are some examples of how this command can be used. This page was created with the easiest, but not necessarily recommended solution first, to the most difficult solution but recommended method last.

@echo off
cls
:start
echo This is a loop
goto start

In this first example, the computer will print “This is a loop” over and over until you terminate the file. To cancel this example press: CTRL + C.

@echo off
cls
:start
echo This is a loop
pause
goto start

Next, adding the pause statement before the goto line will prompt the user to press any key before looping the batch file. This is helpful and recommended to help prevent the computer from utilizing all or most of its resources in having to continuously rerun the loop and will allow the user to rerun the batch when they’re ready.

@echo off
cls
:start
echo This is a loop
set choice=
set /p choice=”Do you wish to restart? Press ‘y’ and enter for Yes: ”
if not ‘%choice%’==” set choice=%choice:~0,1%
if ‘%choice%’==’y’ goto start

Finally, in this last example and most recommend method, the user would be prompted if they wish to rerun the batch file. Pressing “y” would use the goto command and go back to start and rerun the batch file. Pressing any other key would exit the batch file. This example is for Windows 2000, XP and later users if you’re running earlier Windows 98 or earlier you’d need to use the choice command.

Note: Replacing the “echo This is a loop” line with your batch file will allow any of your batch files to loop or rerun.

No Comments

Post a Comment