Skip to main content

How to Create an Infinite Loop in Batch Script

An infinite loop is a sequence of instructions that will repeat forever unless explicitly stopped. While a bug can accidentally create an unwanted infinite loop, they are also a powerful and intentional construct for certain types of scripts. They are the foundation of "daemon" or "service-like" scripts that need to run continuously, such as monitoring a folder for new files, checking a server's status, or keeping a program alive.

This guide will teach you the standard and simplest way to create an intentional infinite loop using a GOTO command that jumps back to a starting label. You will also learn the critical importance of including a "pause" inside your loop to prevent it from consuming 100% of your CPU.

What is an Infinite Loop and Why Use One?

An infinite loop is a control flow structure that executes a block of code repeatedly without a built-in exit condition. The loop will continue until the user manually intervenes (e.g., by closing the command prompt window) or the script is terminated by the system.

Common Use Cases:

  • Monitoring: Repeatedly checking a system status, a folder's contents, or a network connection.
  • Service Emulation: Keeping a command-line application running, automatically restarting it if it crashes.
  • Main Menu: Returning to a main menu after a user's chosen task is complete.

The Core Method: The GOTO Loop

The simplest and most common way to create an infinite loop in a batch script is with a label and a GOTO command.

The pattern:

  1. Define a label at the start of the block of code you want to repeat (e.g., :LoopStart).
  2. Write the commands you want to execute inside the loop.
  3. End the block with a GOTO command that jumps back to the starting label (e.g., GOTO :LoopStart).

Basic Example: A Simple Repeating Message

This script will print a message to the screen over and over, as fast as it can.

@ECHO OFF
:Loop
ECHO This message will repeat forever.
GOTO :Loop

If you run this script, your command prompt will be flooded with the message, and you will have to manually close the window to stop it.

The Critical Step: Preventing 100% CPU Usage

The basic loop from the previous example is a "tight loop." It has no pause, so it will execute as fast as the computer's processor will allow. This will immediately cause one of your CPU cores to spike to 100% utilization, slowing down your entire system. This is highly inefficient and undesirable.

The Solution: Always include a pause or "sleep" command inside your loop. The standard, built-in command for this is TIMEOUT.

Example of a script with a pause

@ECHO OFF
:Loop
ECHO This message will repeat every 5 seconds.
REM The TIMEOUT command pauses the script.
REM /T 5: Wait for 5 seconds.
REM /NOBREAK: Prevents a keypress from interrupting the timeout.
REM > NUL: Hides the "Waiting for..." message.
TIMEOUT /T 5 /NOBREAK > NUL

GOTO :Loop

This version is far more efficient. It runs the ECHO command, then sleeps for 5 seconds, using virtually no CPU during the wait. This is the correct and professional way to write an infinite loop.

How to Stop an Infinite Loop

An intentional infinite loop has no GOTO :EOF or EXIT command. To stop it, you must use one of these manual methods:

  1. Close the Command Prompt Window: Simply click the "X" on the window title bar.
  2. Use Ctrl+C: Press Ctrl+C in the command prompt window. This will trigger a prompt: Terminate batch job (Y/N)?. Pressing Y and then Enter will stop the script.

Common Pitfalls and How to Solve Them

  • Forgetting the Pause: This is the biggest mistake. A loop without a TIMEOUT or SLEEP command will lock up a CPU core. Solution: Always include a TIMEOUT /T N > NUL in any infinite loop.
  • Variable Expansion: If you are changing and reading variables inside your loop, you will likely need to use Delayed Expansion (SETLOCAL ENABLEDELAYEDEXPANSION and !MyVar!) to get their current values on each iteration.

Practical Example: A Simple Server Status Monitor

This script is a perfect real-world use case. It runs forever, pinging a server every minute to check if it's online and logging the status with a timestamp.

@ECHO OFF
SETLOCAL
SET "TARGET_SERVER=google.com"
SET "LOG_FILE=server_monitor_log.txt"

ECHO --- Starting Server Monitor ---
ECHO Monitoring: %TARGET_SERVER%
ECHO Press Ctrl+C to stop.
ECHO.

:MonitorLoop
REM Ping the server once.
PING -n 1 "%TARGET_SERVER%" | FIND "Reply from" > NUL

REM Check the result of the FIND command.
IF %ERRORLEVEL% EQU 0 (
SET "Status=Online"
) ELSE (
SET "Status=Offline"
)

REM Log the result with a timestamp.
SET "Timestamp=%DATE% %TIME%"
ECHO %Timestamp% - Server %TARGET_SERVER% is %Status%. >> "%LOG_FILE%"
ECHO %Timestamp% - Status: %Status%

REM Wait for 60 seconds before checking again.
TIMEOUT /T 60 /NOBREAK > NUL

GOTO :MonitorLoop

Conclusion

Intentional infinite loops are a powerful tool for creating scripts that perform continuous monitoring or service-like tasks. The GOTO :Label pattern is the simple and standard way to construct them.

For reliable and efficient infinite loops, always remember these two critical rules:

  1. Always include a pause inside the loop, preferably using the TIMEOUT command, to prevent 100% CPU usage.
  2. Be aware that you will need to manually stop the script using Ctrl+C or by closing the window.

By following these guidelines, you can safely create continuous-running scripts that are both powerful and system-friendly.