ZetCode

Windows Command Prompt Control Flow

last modified July 14, 2025

Control flow in Command Prompt refers to how commands are executed sequentially or conditionally. Batch scripts use control structures to make decisions and repeat actions. These include if statements for conditional execution and various loops for repetition. Understanding control flow is essential for writing effective automation scripts.

The Command Prompt provides basic programming constructs despite being a simple shell. Control flow commands enable scripts to adapt to different conditions. They can respond to user input, file existence, or variable values. Proper use of control flow makes scripts more robust and flexible.

This tutorial covers all major control flow structures in cmd.exe. We'll explore conditional statements, different loop types, and error handling. Each concept is demonstrated with practical examples. By the end, you'll be able to write complex batch scripts with proper flow control.

Basic Definitions

Control flow structures determine the execution order of commands in a script. They include conditionals that execute code based on tests and loops that repeat code blocks. Batch files use these to create flexible automation.

Conditional statements evaluate expressions and choose execution paths. The primary conditional in cmd is the if statement. It can compare strings, check file existence, or evaluate error levels. Nested ifs handle multiple conditions.

Looping constructs repeat command blocks until conditions are met. Cmd supports for loops (iterating through sets) and GOTO-based loops. Each serves different purposes in batch scripting. Loops process files, directories, or input data.

Error handling manages unexpected conditions during execution. The ERRORLEVEL variable and conditional execution operators (&&, ||) help handle errors. Proper error handling makes scripts more reliable in production environments.

Simple if Statement

The if statement executes commands when a condition is true. This example demonstrates basic string comparison and conditional execution.

if_example.bat
@echo off
set /p user_input=Enter yes or no: 

if "%user_input%"=="yes" (
    echo You entered yes
) else if "%user_input%"=="no" (
    echo You entered no
) else (
    echo Invalid input
)

This script prompts for input and responds differently based on the value. The if statement checks multiple conditions using else if clauses.

set /p user_input=Enter yes or no:

Prompts the user to enter text and stores it in user_input. The /p option makes set wait for user input before continuing.

if "%user_input%"=="yes" (
    echo You entered yes
)

Compares the user_input variable with "yes". If equal, executes the code block. Quotes handle empty input safely.

) else if "%user_input%"=="no" (
    echo You entered no
)

Checks another condition if the first fails. else if allows multiple exclusive conditions in one statement.

) else (
    echo Invalid input
)

Executes when no previous conditions were met. The else clause handles all remaining cases not explicitly checked.

Random Number Generator with Conditional Branching

You can use the %RANDOM% variable to generate random numbers in batch scripts. This example generates a random number between 1 and 100, then uses if to branch based on whether the number is even or odd.

random_example.bat
@echo off
set /a num=%RANDOM% %% 100 + 1
set /a rem=num %% 2

echo Random number: %num%
if %rem%==0 (
    echo The number is even.
) else (
    echo The number is odd.
)

This script prints a random number and tells you if it is even or odd. %RANDOM% produces a pseudo-random integer each time it is referenced.

Checking File Existence

if can check if files exist before operating on them. This prevents errors in file processing scripts.

file_check.bat
@echo off

if exist "config.ini" (
    echo Config file found
    type config.ini
) else (
    echo Config file missing
    echo Creating default config...
    echo [Settings] > config.ini
    echo Theme=Dark >> config.ini
)

This script checks for a configuration file. If missing, it creates a default version. The EXIST condition tests file presence.

if exist "config.ini" (
    echo Config file found
    type config.ini
)

Tests if config.ini exists in current directory. If true, displays its contents. Quotes allow spaces in filenames.

) else (
    echo Config file missing
    echo Creating default config...
)

Executes when file doesn't exist. Informs user and prepares to create default configuration.

echo [Settings] > config.ini
echo Theme=Dark >> config.ini

Creates new config.ini with basic settings. > overwrites, >> appends to file. These redirection operators are powerful.

C:\Users\Jano>file_check.bat
Config file missing
Creating default config...

C:\Users\Jano>file_check.bat
Config file found
[Settings]
Theme=Dark

First run creates the file, subsequent runs display it. This pattern is common in initialization scripts.

For Loop with Files

For loops process sets of items like files or lines. This example processes all text files in a directory.

for_files.bat
@echo off

echo Processing text files:

for %%f in (*.txt) do (
    echo Found: %%f
    echo Size: %%~zf bytes
    echo Last modified: %%~tf
)

The script finds all .txt files and counts their lines. The for loop iterates over each file matching the pattern.

The %%~zf modifier gets the size of the file, and %%~tf gets the last modified timestamp.

Nested if with ERRORLEVEL

ERRORLEVEL checks exit codes from programs. This example demonstrates nested conditionals based on command success.

errorlevel_example.bat
@echo off
ping -n 1 google.com

if errorlevel 1 (
    echo Ping failed
    if exist backup_connection.bat (
        echo Trying backup connection...
        call backup_connection.bat
    ) else (
        echo No backup available
    )
) else (
    echo Ping successful
)

This script checks network connectivity and has fallback logic. Nested ifs handle multiple failure scenarios.

ping -n 1 google.com

Tests network connectivity with one ping packet. Success sets ERRORLEVEL 0, failure sets 1 or higher.

if errorlevel 1 (
    echo Ping failed
)

Checks if ERRORLEVEL is 1 or greater. This means ping failed. ERRORLEVEL checks are common in batch scripts.

if exist backup_connection.bat (
    echo Trying backup connection...
    call backup_connection.bat
)

Nested condition checks for backup script. If exists, executes it. The call command runs another batch file.

Goto Loop with Counter

The goto creates loops by jumping to labels. This example counts down with a delay between iterations.

goto_loop.bat
@echo off
set count=5

:loop
if %count% leq 0 goto end
echo Countdown: %count%
set /a count-=1
ping -n 2 127.0.0.1 >nul
goto loop

:end

echo Blast off!

The script counts down from 5 with 1-second delays. The goto creates the loop structure with a label.

set count=5
:loop
if %count% leq 0 goto end

Initializes counter and starts loop. The leq means "less or equal". When count reaches 0, jumps to :end.

ping -n 2 127.0.0.1 >nul

Creates 1-second delay. Each ping waits 1 second, -n 2 means two pings. The >nul hides ping output.

goto loop
:end

Returns to :loop label for next iteration. :end marks the exit point after loop completes.

C:\Users\Jano>goto_loop.bat
Countdown: 5
Countdown: 4
Countdown: 3
Countdown: 2
Countdown: 1
Blast off!

The countdown shows with 1-second intervals.

Interactive Menu with choice

The choice command lets you create interactive menus in batch scripts. It waits for the user to press a key and sets the ERRORLEVEL variable based on the selection. This is useful for simple menus and branching logic.

menu_example.bat
@echo off

:main
cls
echo --- Subroutine Menu ---
echo 1. Greet
echo 2. Show directory
echo 3. Exit

set /p choice=Choose 1-3: 

if "%choice%"=="1" call :greet
if "%choice%"=="2" call :showdir
if "%choice%"=="3" goto end
goto main

:greet
echo Hello from a subroutine!
pause
goto :eof

:showdir
dir /b
pause
goto :eof

:end
echo Exiting script.

This script displays a menu and performs actions based on the user's key press. choice sets ERRORLEVEL to 1, 2, or 3 depending on the option selected. The script loops until the user chooses to exit.

if "%choice%"=="1" call :greet
if "%choice%"=="2" call :showdir
if "%choice%"=="3" goto end

These lines check the user's choice and call the corresponding subroutine. The call command is used to invoke the subroutine.

:greet
echo Hello from a subroutine!
pause
goto :eof

This subroutine displays a greeting message and waits for user input before returning.

Source

Windows Command Reference

This tutorial covered essential control flow structures in Command Prompt. Mastering these concepts enables writing powerful batch scripts for automation.

Author

My name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming.