If

Examples

Using if to verify the presence of a file

The following message appears if Windows 2000 cannot find the file Product.dat:

  if not exist product.dat echo Can't find data file 

Using if to post a message when an error occurs

The following example displays an error message if an error occurs during formatting of the disk in drive A:

  :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 is skipped.

Using if to verify the presence of a directory

The following example tests for the existence of a directory. The if command cannot be used to test directly for a directory, but the null (NUL) device does exist in every directory. Therefore, you can test for the null device to determine whether a directory exists.

  if exist c:mydir\nul goto process 

Using the else clause

The else clause must occur on the same line as the command after the if. For example:

    IF EXIST filename. (
        del filename.
    ) ELSE (
        echo filename. missing.
    )

The following does not work, because the del command must be terminated by a newline:

    IF EXIST filename. del filename. ELSE echo filename. missing

The following does not work, because the else command must be on the same line as the end of the if command:

    IF EXIST filename. del filename.
    ELSE echo filename. missing

The following form of the original statement works, if you want to format it all on a single line:

    IF EXIST filename. (del filename.) ELSE echo filename. missing