Batch file if else

In this tutorial, you will learn about decision making structures that are the batch file if else statements.

If else statement: Introduction
If else statement syntax
Batch if else examples

if else batch file

Basically programming logic is all about True (1) or False (0). Like any other programming language, batch file if else statements facilitate us to make a decision between true/false or multiple options by imposing a particular condition.

Batch file if else statement

– Syntax

if (condition) dosomething

:: For if..else if
if (condition) (statement1) else (statement2)

So, as the syntax signifies, first a condition is checked and if true, the corresponding statements are executed in the batch file if statement. As for batch file if else, first a condition of if statement is checked and if true, the statement1 is executed else statement2 is executed.

Batch File If Else Flowchart

Here is a flowchart to highlight the concept of if else statement.

batch file if else

Now that we have known about how batch file if else works, let’s go through some examples.


Batch File If Else Example: Checking Integer Variables And String Variables

To know in depth and details about batch file variables, go through this article.

SET /A a=2
SET /A b=3
SET name1=Aston
SET name2=Martin

:: Using if statement
IF %a%==2 echo The value of a is 2
IF %name2%==Martin echo Hi this is Martin

:: Using if else statements
IF %a%==%b% (echo Numbers are equal) ELSE (echo Numbers are different)
IF %name1%==%name2% (echo Name is Same) ELSE (echo Name is different)

Now this will generate following output.

batch file if else output

Batch File If Else Example To Check If Variable Is Defined Or Not

@echo OFF

::If var is not defined SET var = hello
IF "%var%"=="" (SET var=Hello)

:: This can be done in this way as well
IF NOT DEFINED var (SET var=Hello)

Either way, it will set var to 'Hello' as it is not defined previously.

Batch File If Else Example To Check If A File Or Folder Exists

EXIST command is used to check if a file exists or not. Read this article to know details of EXIST and all the other batch file commands.

@echo OFF

::EXIST command is used to check for existence
IF EXIST D:\abc.txt ECHO abc.txt found
IF EXIST D:\xyz.txt (ECHO xyz.txt found) ELSE (ECHO xyz.txt not found)


Now, let’s assume we have "abc.txt" in D drive and "xyz.txt" doesn’t exist in D: , then it will generate following output.

batch file if exist

So, that’s all about batch file if else statements. We hope you didn’t have a hard time learning about it and hopefully, by this time, you will know how to use if else in batch file scripting.