CMD Master
Back to Blog
Arnošt Havelka

Advanced Batch

Master loops, conditions, and flow control.

Start Interactive Lesson
Advanced Batch

Advanced Batch Control

Once you can write simple linear scripts, it's time to add logic. Batch files support conditional execution (if), loops (for), and jumping to specific sections (goto).

Usage:if
[condition]
(command)
else (command)
exist
Checks if a file exists.
not
Inverts the condition.
errorlevel
Checks the exit code of the previous command.

Flow Control Concepts

1. Conditional Execution (IF)

Execute commands only when certain conditions are met.

if exist config.txt (
    echo Config found!
) else (
    echo Config missing!
)

2. Loops (FOR)

Repeat a command for a set of files or numbers.

:: Print numbers 1 to 5
for /L %%i in (1,1,5) do echo %%i

3. Goto and Labels

Jump to different parts of your script.

:Start
echo Working...
goto End

:End
echo Done.

Real-World Examples

1. Creating a backup if a file exists

Safeguard your data automatically.

Command Prompt
C:\Users\User>if exist data.txt copy data.txt data.bak

2. Looping through files

Process every .txt file in the current folder.

Command Prompt
C:\Users\User>for %f in (*.txt) do echo Found %f

(Note: Use %f in command line, but %%f in batch files)


Knowledge Check

1 / 3

Which keyword is used for conditional logic?