Table of Contents

Dos - If

About

To get more help on the if statement, type on the command line prompt:

help if

Syntax

Statement

If Else

IF condition (
   command
   ) ELSE (
   command
   )

where:

When using the else construct:

IF condition (command) ELSE command

Short If

IF condition command

Condition

text and number comparison

Syntax
[/I] [NOT] string1==string2

and

[/I] string1 compare-op string2

where

Example
@echo off
set hello=hello
if "%hello%"=="hello" echo %hello% world
hello world

if 2 GTR 1 (echo Yes) else echo No
Yes

exist

Syntax
[NOT] EXIST filename

where:

Example
@echo off
if exist hello.bat (
    echo hello.bat exist
    )
hello.bat exist

Errorlevel

Without comparison

Syntax:

ERRORLEVEL number 

This condition will return a true condition if the last program run returned an exit code (Errorlevel) equal to or greater than the number specified. When a command executes without error it terminates with an exit status of zero.

With comparison

With the string comparison

[NOT] %ERRORLEVEL% [compare-op]  number 

where:

See Error level example

Defined

Syntax:

[NOT] DEFINED variableName

Example:

if not defined v (echo v is not defined) else echo %v%
v is not defined

set v=Call Me Nico
if not defined v (echo v is not defined) else echo %v%
Call Me Nico

Support

was unexpected at this time.

This error occurs really often when you test a condition over a variable that is not set.

The command interpreter first replace the variable with its value before starting the command and the result is an error in the syntax as the variable has no value.