By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

Batch If Else Statements

Tutorial on how to work with If Else Statements in batch programs.

Created: 2012-02-25 17:47

In batch files, it is possible to do conditional checks using Batch If and Else commands.

Check if a file exists in Batch

If the file is found, it will be deleted, otherwise an error message is shown.

@echo off
IF EXIST MyFileName.txt (
del null.
) ELSE (
echo MyFileName.txt is missing.

Using labels in batch files

You can also use goto :label in your statements, so in this case we goto the :success, if errorlevel was not 1.

Note. The errorlevel variable is set by the previous program run by cmd.exe.

@echo off
@format a:
if not errorlevel 1 goto success
echo An error occurred during formatting.
echo A disk in drive A: appears to have been formated successfully.