The Ultimate Guide To Batch File Programming PART- 6

The If statement is a very useful command which allows us to make the batch files more intelligent and useful. Using this command one can make the batch programs check the parameters and accordingly perform a task. Not only can the IF command check parameters, it can also checks if a particular file exists or not. On top of all this, it can also be used for the conventional checking of variables (strings).

batch file programming

Checking If a File Exists Or Not
The general syntax of the IF command which checks for the existence of a file is the following:


This will become clearer when we take up the following example,

IF EXIST c:\autoexec.bat ECHO It exists

This command checks to see if the file, c:\autoexec.bat exists or not. If it does then it echoes or prints the string 'It exists'. On the other hand if the specified file does not exist, then it does not do anything.

In the above example, if the file autoexec.bat did not exist, then nothing was executed. We can also put in the else clause i.e. If the File exists, do this but if it does not exists, by using the GOTO command. Let's consider the following example to make it more clear:

@echo off
Goto end

The IF statement in this code snippet checks to see if there exists a file, c:\ankit.doc. If it does then DOS is branched to :THA and if it does not, then DOS goes on to the next line. The next line branches DOS to :end. The :end and :THA in the above example are called labels. After the branching the respective echo statements take over.

IMPORTANT: We can also check for more than one file at a time, in the following way:
IF EXIST c:\autoexec.bat IF EXIST c:\autoexec.bak ECHO Both Exist

We can check to see if a file does not exist in the same way, the basic syntax now becomes:


For Example,

IF NOT EXIST c:\ankit.doc ECHO It doesn't Exist

How do you check for the existence of directories?

No something like IF C:\windows EXISTS ECHO Yes does not work. In this case we need to make use of the NULL device. The NULL device is basically nothing, it actually stands for simply nothing. Each directory has the NULL device present in it. (At least DOS thinks so.) So to check if c:\windows exits, simply type:

IF EXIST c:\windows\nul ECHO c:\Windows exists.

One can also check if a drive is valid, by giving something like:

IF EXIST c:\io.sys ECHO Drive c: is valid.

AbhiShek SinGh
Founder of 'TheHackingArticles'. Cyber Security Analyst, Cyber Security Researcher, and Software Engineer. Follow 'AbhiShek SinGh' on Facebook , Twitter or Google+ or via Email

Subscribe to stay up to date