How to Use IF...ELSE Statements in Batch Script
Conditional logic is the heart of any useful program, and in batch scripting, the primary tool for this is the IF statement. While a simple IF can run a command when a condition is true, the real power comes from the IF...ELSE structure. This allows you to create two distinct paths of execution: one for when the condition is met, and another for when it is not.
This guide will teach you the correct syntax for constructing IF...ELSE statements in a batch script. You will learn the critical placement of the parentheses and the ELSE keyword, and see practical examples of how this structure is used to handle different outcomes, such as a command succeeding or failing.
The Core Command: IF
The IF command evaluates a condition and, if it's true, executes a command. There are several types of conditions it can check:
IF EXIST filename: Checks if a file exists.IF %var1% EQU %var2%: Checks if two numbers are equal.IF "%str1%"=="%str2%": Checks if two strings are identical.IF DEFINED varname: Checks if a variable has been defined.
The IF...ELSE Structure
The ELSE clause provides an alternative action to be performed only if the initial IF condition is false. This creates a clear "this or that" decision point in your script.
The syntax is very specific and must be followed exactly:
IF (condition) (DoThis) ELSE (DoThat)
For readability with multiple commands, this is written across several lines.
Basic Example: A Simple File Check
This script checks if a log file exists. It will print one message if the file is found and a different message if it is not.
@ECHO OFF
SET "LOG_FILE=application.log"
ECHO Checking for "%LOG_FILE%"...
IF EXIST "%LOG_FILE%" (
ECHO [SUCCESS] The log file was found.
) ELSE (
ECHO [FAILURE] The log file is missing.
)
ECHO.
ECHO Check complete.
Output (if application.log exists)
Checking for "application.log"...
[SUCCESS] The log file was found.
Check complete.
Output (if application.log does not exist)
Checking for "application.log"...
[FAILURE] The log file is missing.
Check complete.
How the IF...ELSE Syntax Works
The structure ) ELSE ( is the key to making this work. Let's break down the parsing:
IF (condition) (command_block_1) ELSE (command_block_2)
IF (condition): TheIFstatement and its condition.(command_block_1): A parenthesized block of one or more commands to run if the condition is true. The opening parenthesis(must be on the same line as theIF.ELSE: This keyword must immediately follow the closing parenthesis)of the "true" block.(command_block_2): A parenthesized block of commands to run if the condition is false. The opening parenthesis(must be on the same line as theELSE.
This strict syntax is what allows the cmd.exe parser to understand the entire statement as a single, logical unit.
5. Using IF...ELSE with Multi-line Command Blocks
The real power of this structure is in executing multiple commands for each case.
@ECHO OFF
SET "BACKUP_DIR=E:\Backups"
IF EXIST "%BACKUP_DIR%\" (
ECHO Backup directory found.
ECHO Running cleanup process...
REM (More commands could go here)
) ELSE (
ECHO Backup directory not found!
ECHO Creating it now...
MKDIR "%BACKUP_DIR%"
ECHO Please run the script again to perform the backup.
)
6. Common Pitfalls and How to Solve Them
6.1. Problem: "ELSE is not a valid command." (Incorrect Syntax)
This is the most common error. It happens when the ELSE keyword is not on the same line as the closing parenthesis ) of the IF block.
The Error in Action
REM This is WRONG and will cause a syntax error.
IF EXIST "file.txt" (
ECHO Found it.
)
ELSE (
ECHO Missing.
)
The Solution: The ) ELSE ( Structure
You must place the closing parenthesis of the IF block, the ELSE keyword, and the opening parenthesis of the ELSE block on the same line.
REM This is the CORRECT syntax.
IF EXIST "file.txt" (
ECHO Found it.
) ELSE (
ECHO Missing.
)
6.2. Problem: Checking for NOT Conditions
The IF command has a built-in NOT operator that can simplify your logic by inverting the condition.
Without NOT
IF EXIST "file.txt" (
REM Do nothing
) ELSE (
ECHO The file is missing.
)
This is awkward.
With NOT (Recommended)
IF NOT EXIST "file.txt" (
ECHO The file is missing.
) ELSE (
ECHO The file was found.
)
This is much cleaner and more readable. The NOT operator can be used with most IF conditions (NOT DEFINED, NOT %A% EQU %B%, etc.).
7. Practical Example: Checking a Command's Exit Code
This is a perfect use case for IF...ELSE. The script runs a command and then immediately takes one of two actions based on whether the command succeeded (%ERRORLEVEL% is 0) or failed.
@ECHO OFF
SETLOCAL
ECHO Attempting to connect to the server...
PING -n 1 a-real-server.com > NUL
IF %ERRORLEVEL% EQU 0 (
ECHO [SUCCESS] The server is online.
ECHO Proceeding with the main task...
) ELSE (
ECHO [FAILURE] The server is offline.
ECHO Please check your network connection and try again.
)
ENDLOCAL
This script provides clear, immediate feedback for both the success and failure cases.
8. Conclusion
The IF...ELSE statement is the fundamental tool for creating decision-making logic in batch scripts. It provides a clear and structured way to handle different outcomes.
Key takeaways for using it successfully:
- Use the
IF (condition) (...) ELSE (...)structure to define two distinct code paths. - Strictly follow the syntax: the
) ELSE (part must be on a single line. - Use
IF NOTto create more readable logic for negative conditions. - This structure is essential for robust error handling by checking
%ERRORLEVEL%.
By mastering the IF...ELSE statement, you can move beyond simple linear scripts and start creating powerful automation that can react intelligently to different situations.