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:
- The command needs to be terminated by a newline or the block command must be defined with brackets.
- The else statement must be in the same flow than the if
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
- the /I switch specify a case insensitive comparison.
- compare-op may be one of:
- EQU - equal
- NEQ - not equal
- LSS - less than
- LEQ - less than or equal
- GTR - greater than
- GEQ - greater than or equal
Example
- Text Comparison
@echo off
set hello=hello
if "%hello%"=="hello" echo %hello% world
hello world
- Number
if 2 GTR 1 (echo Yes) else echo No
Yes
exist
Syntax
[NOT] EXIST filename
where:
- the parts enclosed between bracket are optional (ie NOT)
- filename is the name of the file
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:
- %ERRORLEVEL% is the dynamic variable of ERRORLEVEL
- compare-op can be one of the following
- EQU - equal
- NEQ - not equal
- LSS - less than
- LEQ - less than or equal
- GTR - greater than
- GEQ - greater than or equal
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.