Perform conditional processing in batch programs.
IF [NOT] ERRORLEVEL number command
IF [NOT] string1==string2 command
IF [NOT] EXIST filename command
| NOT | Specifies that Windows NT should carry out the command only if the condition is false. |
| ERRORLEVEL number | Specifies a true condition if the last program run returned an exit code equal to or greater than the number specified. |
| command | Specifies the command to carry out if the condition is met. |
| string1==string2 | Specifies a true condition if the specified text strings match. |
| EXIST filename | Specifies a true condition if the specified filename exists. |
| MS-DOS and PC-DOS (incl. Win95's MS-DOS 7) |
as described above |
| OS/2 Warp | as described above |
| Windows NT 4/2000/XP | special features: compare numbers, case insensitive matching, and more |
| 1. | When comparing strings, make sure neither of them is empty or contains
spaces only (both leading and trailing spaces are ignored). Empty strings can be prevented easily by adding some meaningless but non-empty string at both sides of the equal sign: IF X%1==X/? GOTO HelpscreenEven if no parameter is given (in which case %1 is an empty string) the string before the equal sign won't be empty. A commonly used way to prevent empty strings is enclosing them in either quotes or (square) brackets: IF "%1"=="/?" ... orIF [%1]==[/?] ... |
| 2. | Matches should be exact; none of the strings "abc", "Abc" and "ABC"
match. Only NT provides case insensitive matches using the /I option: IF ABC==abc evaluates to "false",IF /I ABC==abc evaluates to "true" |
| 3. | In DOS, IF EXIST only checks for the existence of files.Since DOS' devices AUX, COMn, LPTn, NUL and PRN are also treated as files, and they exist in every directory, one way to check for the existence of a directory would be: IF EXIST C:\TEMP\NUL SET TEMP=C:\TEMPNote, however, that you will lose one file handle for each directory you perform this check on, since this check opens the (NUL) device using a file handle, but the device will never be closed again until the next reboot. Note also, that NUL doesn't exist on every type of drive in every DOS version. Try IF EXIST D:\NUL.EXT ....
if you have to access CD-ROM's or network drives.If all you want to do is create a directory if it does not exist, use XCOPY /S /E ... to copy a dummy file to that
directory, check for existance of the copied dummy file, and delete
it afterwards. |
| 4. | When checking errorlevels, keep in mind that checking for errorlevel
3 will return TRUE if the errorlevel is 3 or higher! If you want to check if an errorlevel is exactly equal to 3, use IF ERRORLEVEL 3 IF NOT ERRORLEVEL 4 .....This will return TRUE if both conditions (greater than or equal to 3 AND NOT greater than or equal to 4) are met, in this case only if the errorlevel is exactly 3. |
| 5. | Most (but not all) OS/2 and NT commands return a non-zero return code
(errorlevel) on failure. Don't count on it in DOS, though. |