Performs conditional processing in batch programs.
if [not] errorlevel number command [else expression]
if [not] string1==string2 command [else expression]
if [not] exist FileName command [else expression]
If command extensions are enabled, use the following syntax:
if [/i] string1 CompareOp string2 command [else expression]
if cmdextversion number command [else expression]
if defined variable command [else expression]
not : Specifies that the command should be carried out only if the condition is false.
errorlevel number : Specifies a true condition only if the previous program run by Cmd.exe returned an exit code equal to or greater than number.
command : Specifies the command that should be carried out if the preceding condition is met.
string1==string2 : Specifies a true condition only if string1 and string2 are the same. These values can be literal strings or batch variables (for example, %1). You do not need to use quotation marks around literal strings.
exist FileName : Specifies a true condition if FileName exists.
CompareOp : Specifies a three-letter comparison operator. The following table lists valid values for CompareOp.
/i : Forces string comparisons to ignore case. You can use /i on the string1==string2 form of if. These comparisons are generic, in that if both string1 and string2 are both comprised of all numeric digits, the strings are converted to numbers and a numeric comparison is performed.
cmdextversion number : Specifies a true condition only if the internal version number associated with the Command Extensions feature of Cmd.exe is equal to or greater than number. The first version is 1. It is incremented by one when significant enhancements are added to the command extensions. The cmdextversion conditional is never true when command extensions are disabled (by default, command extensions are enabled).
defined variable : Specifies a true condition if variable is defined.
expression : Specifies a command-line command and any parameters to be passed to the command in an else clause.
/? : Displays help at the command prompt.
If the file Product.dat cannot be found, the following message appears:
if not exist product.dat echo Can't find data file
If an error occurs during the formatting of the disk in drive A, the following example displays an error message:
:begin @echo off format a: /s if not errorlevel 1 goto end echo An error occurred during formatting. :end echo End of batch program.
If no error occurs, the error message does not appear.
You cannot use the if command to test directly for a directory, but the null (NUL) device does exist in every directory. As a result, you can test for the null device to determine whether a directory exists. The following example tests for the existence of a directory:
if exist c:\mydir\nul goto process