In this, you learned about if block conditional expressions in DOS batch programming

  • if block
  • if-else block
  • nested if

if block example

if in the batch are used to evaluate conditional expressions and execute the lines of code based on the conditional result.

if(conditionexpression) code

a conditional expression is true, executes code.

@echo off
SET  active= true
SET  name= john
if %active%==true echo active is true
if %name%==eric echo name is not john

And output

active is true

conditional expressions are evaluated to be true or false and execute code based on it.

These expressions are case-sensitive.

If else in batch programs

It executes conditional express with if and else blocks

If (expressions) (codeblock1) ELSE (codeblock2)

if the expression is true, codeblock1 executes, else i.e. false, codeblock2 is executed.

codeblock1 and codeblock2 wraps inside ().

Here is an if else example

@echo off
SET  active= false
if %active%==true (echo active is true) else (echo active is not true)

Output:

active is not true

The above variable is evaluated in if block and based on the result if block or else block is executed.

nested if-else blocks

nested if blocks are defined in another if blocks.

here is a syntax.

if(expression1) if (expression2) codeblock

if expression1 is true, Then expression2 is evaluated and if true, the code block is executed.

You can also include an if-else block inside the if block.

Here is an example

@echo off
SET  active= true
SET name= john
if %active%==true if %name%==john echo "name=john and active=true"

Output:

name=john and active=true

How to check variable exists in DOS batch programming?

if defined is used to check variable exists or not.

  • Syntax

if the defined variable code block

if the variable is defined, the code block executes Here is an example

@echo off
SET  dept= sales
if defined dept (echo variable dept exists) else (echo variable dept not exist)

Output:

variable dept exists

defined can be used with if block as well as nested if-else blocks