IF statement in DOS batch file

This article is from our Febooti archive, it was relevant then, and I think that it is still relevant today (a few details changed).
Previous article: Loops in the Batch files with examples.

console-dos-1-small

The IF command in the batch scripting is very similar to the IF statement in other programming languages. The IF command allows you to branch the execution of the batch file into two separate paths depending on some condition.

The basic syntax of IF command is:
IF {Statement} {If statement is TRUE, perform this action}

If the statement being tested is TRUE, then perform the action on the same line (to the right side of IF). If the statement is FALSE, then continue to the next line. The TRUE action statement is, essentially, ignored in case of FALSE. A GOTO command could perhaps be present on this line to send processing of the batch file to another location in the script. The IF command is great for testing three types of conditions including replaceable parameters, system ERRORLEVEL, and it can compare two strings.

Remember that several IF commands can be stacked one after another, to test more conditions, or to create tree like algorithms. An algorithm is simply your solution to the problem at hand.

Here is an example that tests replaceable parameters (Note that on some versions of Windows or a different configuration of your command prompt might change how this example is run. Play around with it and your CMD interpreter settings):
:: LOOP.BAT
:: Compares Replaceable parameters.
@ECHO OFF
:TOP
   IF (%1)==() GOTO END
   ECHO Value is "%1" and still running...
   SHIFT
GOTO TOP
:END

Loop.bat executed with 3 parameters on the Windows 8.1
Loop.bat executed with 3 parameters on the Windows 8.1

The first two lines are remark statements indicating the name of the program as well as a brief description of what the program does. The third line brings command echoing to a standstill. Line four marks off the label for sub program that a GOTO command could hop to. Line 5 tests for a blank (empty) replaceable parameter. When %1 contains any information then that information gets placed in the first set of parentheses (parameter)==() and evaluates to FALSE. This is what we want. A common mistake is to omit the parentheses, however we need them so we do not create an infinite loop.

When replaceable parameter %1 is empty, the test becomes ()==() and appropriately evaluates to TRUE. This line is the core code of this batch script. When the expression evaluates to TRUE the GOTO END command is executed. This essentially ends the program. When the expression (condition) is FALSE, the next line of code is executed. The sixth line displays the value of parameter combined in message, Value is “something” and still running… using the ECHO command. That next line of code contains the SHIFT command. We know that the SHIFT command shifts the values of replaceable parameters over. The last line is the END label symbolizing the end of the program.

Note that the indents do not change your code and are not mandatory, however it is easier to read code if we indent everything inside the IF block.

The IF command is a handy command by itself, however it yields great possibilities when combined with other commands. Such as the EXIST command. The EXIST command is used to test the existence of a file. This can be done using the following syntax scheme:

IF EXIST command syntax:
IF EXIST {filename} {If filename exist, perform this action}

Lets consider example, where we pass 3 parameters to the batch file, and assume that each of the params is a filename:
:: ExistFile.BAT
:: Example of IF EXIST command sequence.
@ECHO OFF
IF EXIST %1 ECHO File %1 exists!
IF EXIST %2 ECHO File %2 exists!
IF EXIST %3 ECHO File %3 exists!

Example output when passed 3 parameters, and only first file exists. Tested under Windows 8.1
Example output when passed 3 parameters, and only first file exists. Tested under Windows 8.1

Lines 1 and 2 are remark statements indicating the name of the batch file and a brief description of what the batch file does. Line 3 turns off command echoing. Lines 4 through line 6 tests the existence of whatever values are in the replaceable parameters 1, 2, and 3 respectively. This program is rather trivial, but servers as a good example.

Read more in Microsoft help site.

Next article: MS-DOS command redirection operators.

This article is from our Febooti archive, it was relevant then, and I think that it is still relevant today (a few details changed).

Loops in the Batch files with examples

This article is from our Febooti archive, it was relevant then, and I think that it is still relevant today (a few details changed). Previous article: Replaceable parameters in batch file.

WinXP-dir-p

The very simple loop in the batch script can be created by using GOTO command and a label. The syntax is – GOTO followed by the name of the line/label. The label is defined by the colon character at the beginning of the line. The label can be above or below GOTO statement. The code fragment below shows example of infinite loop.

:: LOOP.BAT
:: A batch file example using a infinite loop.
:TOP
DIR
GOTO TOP

The first two lines are remark statements giving the details of the program including the filename and a brief description of the program. The third line marks the line (creates a label) that a GOTO command can possibly link to. The fourth line will perform a directory listing. This is just an example command to illustrate a task that can be performed using the batch loop. You might like to indent the DIR command to emphasize that it is inside a loop. The last line is the command to jump to the line with the name TOP and to continue processing. Since there is no IF statement to test some condition and possibly to jump out of this loop, the batch file will continue to run indefinitely or until you press the CTRL+C or the CTRL+Break combinations on your keyboard.

Loop.bat output under Windows 8.1, Ctrl+C pressed
Loop.bat output under Windows 8.1, Ctrl+C pressed

:: LOOP2.BAT
:: Loop reads multiple replaceable parameters
:: with a SHIFT command inside the loop.
@Echo Off
:TOP
Copy %1 E:\
Shift
Goto TOP

LOOP2.BAT is a more useful program that copies a list of files specified after batch file to the E: drive. When the LOOP2.BAT program runs out of files to copy, the program will not stop. The batch script will attempt to continue until you use CTRL+C or CTRL+Break to terminate the program. To stop the batch script automatically, you need to add IF statement, but we will not discuss it here.

The first three lines are remark statements indicating the name of the batch file and a brief description of the batch file. The fourth line turns off command echoing. Remember that the @ sign turns off the echoing of the ECHO OFF command. The fifth line is the label that the GOTO command will jump to. The sixth line copies the file defined by the first replaceable parameter to the E: (usually flash drive) drive. The seventh line utilizes the SHIFT command to replace %0 with %1, %1 with %2, and so forth. The last line, GOTO TOP, is used to jump to the line labeled TOP and continue processing. Obviously the downside to this looping structure is that it needs more control. As mentioned above, one way to add this control is through the IF statement.

Next article: IF statement in DOS batch file.

This article is from our Febooti archive, it was relevant then, and I think that it is still relevant today (a few details changed).

Update Feb 21, 2015. Added link to the next article.

Replaceable parameters in batch file

This article is from our Febooti archive, it was relevant then, and I think that it is still relevant today (a few details changed).
Previous article: Stopping a DOS batch file.

console-wishmesh
Photo: freeimages.com

With the information covered so far we are able to use batch files to make our lives easier, and help our day to day computing operations. However, we could make our batch scripts more sophisticated by avoiding the big limitation that we have been faced with so far. That is – our files are hard-coded (written in stone, so to speak) and if we want to manipulate a file, we have to change the batch script again and again.

What if we wanted to perform a particular operation on a different file each time? We can use replaceable parameters to help us with this task. The two important factors in using replaceable parameters are – how to code them in the batch file, and second – how to give the values for the replaceable parameters to the batch file. The latter is rather quite easy. Replaceable parameters are to be entered after the batch file name and before pressing the Enter key. For example:

C:\>batch-params.bat Par1 Par2 Par3 Par4 Par5

Either a space or a comma character separates each parameter. Both are treated the same. Now, how many replaceable parameters does the above line have? The obvious answer would be five. This would be wrong. DOS counts the name of the batch file itself as a parameter, so there are 6 replaceable parameters on this line. Much like other programming languages DOS names them %0, %1, %2, %3, %4, %5 rather than %1 through %5.

DOS uses replaceable parameters as if they do not exist – for example, everywhere you see a replaceable parameter, the DOS sees the value of that parameter. When a batch script executes with ECHO ON, the DOS precedes each command in the batch file prompt. DOS treats the commands in the batch file exactly like it would if you entered them from the DOS prompt.

:: batch-params.bat
:: Example with Replaceable Parameters.
ECHO %1
ECHO %2
SHIFT
ECHO %2

The first 2 lines are remark statements that show the name of the file and a brief description of the program. The third line echo’s the first replaceable parameter entered on the command line. If replaceable parameter was not entered, the command will display the Echo is on message (just like with simple ECHO command). The fourth line shows the 2nd parameter. The fifth line shifts the argument. The line 6 acts like line 4, but because of SHIFT, it and echo’s third argument. SHIFT command allows to use more than 10 parameters / arguments in the batch file:

SHIFT changes the values of the batch parameters %0 through %9 by copying each parameter into the previous one. In other words, the value of %1 is copied to %0, the value of %2 is copied to %1, and so on. More in MS Help site.

The SHIFT command discards the first parameter %0, moves the remaining parameters down one value, and brings in a new value if one exists. Therefore after the SHIFT command gets read, the value in %1 is moved into %0, and the value in %2 moves into %1 and so on and so forth.

The SHIFT command really has two major purposes. First, by moving the parameters down into a lower replaceable parameter, a single replaceable parameter may be used for all coding by forcing the batch script to loop through the code. Second, it allows the batch file to handle more than nine replaceable parameters. The total number of replaceable parameters is constrained by the 127-character command line limitation (for old OSes), and starting Windows XP or later you can use longer command line – up to 8191 characters. A space, comma or semicolon is also a requirement to separate each replaceable parameter.

If you start our example batch file with the parameters: text1, text2, text3 and text4, you will see the following output:
C:\>batch-params.bat text1 text2 text3 text4
C:\>ECHO text1
text1
C:\>ECHO text2
text2
C:\>SHIFT
C:\>ECHO text3
text3
C:\>

And, note: we do not access fourth parameter (%4), so it is not shown in the console. Also, see the screenshot from Windows 8.1 CMD.exe:

Showing output example from the batch file with parameters
Showing output example from the batch file with parameters

Next article: Loops in the Batch files with examples.

This article is from our Febooti archive, it was relevant then, and I think that it is still relevant today (a few details changed).

Update Feb 21, 2015. Added link to the next article.