CMD Master
Back to Blog
Arnošt Havelka

Advanced Batch

Master loops, conditions, and flow control.

Start Interactive Lesson
Advanced Batch

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).

Try the command

Check if a file exists!

Build the command
if
Terminal
C:\Users\Student>if exist config.ini (echo Found)
Found

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.

Try the command

Choose an option and the terminal output updates immediately.

Build the command
ifexist data.txt copy data.txt data.bak
Terminal
C:\Users\Student>if exist data.txt copy data.txt data.bak
1 file(s) copied.

2. Looping through files

Process every .txt file in the current folder.

Try the command

Choose an option and the terminal output updates immediately.

Build the command
for%f in (*.txt) do echo Found %f
Terminal
C:\Users\Student\work>for %f in (*.txt) do echo Found %f
Found note.txt Found todo.txt

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


Knowledge Check

1 / 3

Which keyword is used for conditional logic?

References

These documentation links provide authoritative details for the commands used in this article.

Up Next

Practical: Batch Intro

Write your first automation script.