Batch If Else Statements

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

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.
)
pause

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.
pause
:success
echo A disk in drive A: appears to have been formated successfully.
pause

Post comment

Links that you insert are not nofollowed, but will be removed by admins if they are considered spam.

[url=Absolute URL for page]TITLE[/url]

You should insert code boxes around code examples, which will be automatically syntax highlighted.

[code1 html|css|javascript|php|sql]Your Code Here[/code1]

You may want to read our Privacy Policy before submitting your comment.