If

Index

The IF command is used to provide conditional processing in batch programs. If the condition specified by an IF command is true, MS-Dos carries out the command that follows the condition. If the condition is false, MS-Dos ignores the command.

Syntax:

IF [NOT] string1==string2 command

IF [NOT] EXIST filename command

IF [NOT] ERRORLEVEL errlevel command

commandThe command to be carried out if the condition is true
NOTcommand is only carried out if the condition is false.
errlevelThe value of the exit code returned by the last program to terminate.
string1==string2The syntax for comparing two strings.
These values can be literal strings or batch variables (eg. %1). Literal strings do not need quotation marks but it is a good idea to use them so the program won't crash if a comparison is made with a null parameter.

Notes:

When most (if not all) external Dos commands terminate, an exit code is returned to MS-Dos. For example, a value of 0 is typically used to indicate that a program was successfully executed. The ERRORLEVEL parameter enables these exit codes to be used as conditions.

In spite of the syntax indicated above, the IF ERRORLEVEL statement should be interpreted as: IF ERRORLEVEL >= errlevel command. Thus, if a series of tests are being made on an exit code, they must be listed in descending order.

Examples:

To display the message "Can't find data file" if the file "product.dat" is not in the current directory:
IF NOT EXIST product.dat ECHO Can't find data file

To test for the existence of a directory. As it happens, there is no direct test for a directory, but every directory on the hard drive contains the null (NUL) device. Testing for the null device will show whether a directory exists on the hard drive:
IF EXIST c:\mydir\nul GOTO process

This example displays an error message if an error occurs during formatting of the disk in drive A. If no error occurs, the error message is skipped. Note that the test is to determine whether the exit code given by FORMAT is not 1 (or anything more than 1).
:begin
ECHO off
FORMAT a: /s
IF NOT ERRORLEVEL 1 GOTO end
ECHO An error occurred during formatting.
:end
ECHO End of batch program.

File Details:

Internal


If you should have any comments or suggestions,
please contact: Bob Watson
.
This page last revised:
December 9, 1999.