Saturday 9 March 2013

IF: CONDITIONAL BRANCHING

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).
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:
IF [NOT] EXIST FILENAME Command
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
IF EXIST C:\anil.doc GOTO ANIL
Goto end
:ANIL
ECHO ANIL
:end
The IF statement in this code snippet checks to see if there exists a
file, c:\anil.doc. If it does then DOS is branched to :ANIL and if it
does not, then DOS goes on to the next line. The next line branches
DOS to :end. The :end and :ANIL in the above example are called
labels. After the branching the respective echo statements take over.

No comments:

Post a Comment