Question:
Potentially very easy batch file question - loop a few times and exit?
anonymous
2008-12-17 19:35:46 UTC
Short and possibly very easy question, how to make a batch file loop a command twice and then exit.
The commands are long so i don't want to copy and paste it beneath it.
e.g.
:hello
echo hello
goto hello
exit

^ how would i make that run twice WITHOUT copying the "echo hello" beneath it?
Thanks in advance :)
Three answers:
anonymous
2008-12-18 10:56:20 UTC
Loop two or more times you say?



@echo off

set start=0

rem replace the number 2 in the next command

rem with the number of times you wish to loop it.

set end=2

:loop

if %start%==%end% goto stop

rem Your conditions and statements here

set /a start=%start%+1

rem next line to adjust the loop speed

ping localhost -n 1 >nul

cls

goto loop

:stop

rem End of loop

pause







Here's an example of using this, I call it the timer:





@echo off

rem User Input Timer

:top

cls

echo ================

echo Timer

echo ================

echo.

set /p start=Starting Number:

echo.

set /p end=Ending Number:

echo.

set /p rate=Delay Rate:

echo.

echo Press any key to start timer. . .

pause >nul

goto timer

:timer

if %start%==%end% goto stop

echo Timer Progress: %start%

set /a start=%start%+1

if errorlevel 1 goto error

ping localhost -n %rate% >nul

if errorlevel 1 goto error

cls

goto timer

:error

cls

echo There was an error initializing the timer.

echo Please verify that you have specified

echo integer values.

echo.

pause goto top

:stop

cls

echo Timer has completed.

echo.

pause







Here's another example, it's some random folder generator:





@echo off

cd "%userprofile%\Desktop"

if exist "FolderData" goto top

mkdir "FolderData"

:top

cls

set ran=%random%

echo ================

echo Folder Generator

echo ================

echo.

set /p end=Number of Folders to generate:

set start=0

:timer

cd "%userprofile%\Desktop\FolderData"

if %start%==%end% goto stop

set ran=%random%

if exist %ran% goto timer

md %ran%

echo Creating Folders

echo ================

echo.

echo Folders Created: %start%

set /a start=%start%+1

ping localhost -n 1 >nul

cls

goto timer

:stop

cls

echo %start% Folders has been created in

echo %userprofile%\Desktop\FolderData.

echo.

pause

goto top
guilbeaux
2016-11-12 00:29:04 UTC
Loop Batch File
DogmaBites
2008-12-17 19:43:18 UTC
Assuming Windows command line, look up the for command:

help for



for /L %variable in (start, step, end) do command



for /L %i in (1,1,2) do echo hello



You can use the variable %i in your command:

for /L %i in (1,1,2) do echo hello %1

will output:

hello 1

hello 2


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...