windows batch file programming tutorial, how to create dos batch file, guide, tips
Home About Us Reference Product Service Sitemap

Windows batch file programming tutorial


Batch file programming is used to perform tasks from the command line. The script is run as an alternative to running each command by hand. A batch file is actually a text file with DOS commands in it. Each DOS command will be on a seperate line. Then, instead of a .txt extension, it has the extension of .bat. You can double click the batch file or type its name at the DOS prompt to execute the commands.

To create a batch file and if you do not know much about the DOS commands, you need to go to our other section, Learn DOS commands, to learn them first or you can learn a bit about DOS commands in the following.

The main DOS commands we will usually use are copy, move, del, cls, and echo. In the following, we will show you one after another.

COPY

The COPY command is to copy one file from one location to another location. The following is the syntax:

copy [source] [destination]

An example is as follows:

copy a:\test.txt a:\my documents\test1.txt

MOVE

The MOVE command is exactly the same, except it MOVEs the file, and COPY copies the file. The del command is very simple. It erases a file. It follows this syntax:

del [filename]

An example is as follows:

del e:\test.txt CLS

The CLS command clears the screen. This is the syntax:

cls

PAUSE

PAUSE is a command that stops the program and prompts you to "Press any key to continue." The syntax is:

pause

ECHO

ECHO is a DOS command that shows the stuff you type. In a batch program, the @ symbol means not to echo a line. So, typing ECHO OFF prevents the user from watching the batch program execute. And, to keep from echoing the ECHO OFF command, type the @ symbol in front of it. Put it together and you get:

@echo off

Note:

1. Start with the @ECHO OFF command followed by CLS.

2. If you use the @ECHO OFF command in your batch program, be sure to put ECHO ON at the end of the batch program or the user will think their computer is messed up. The ECHO ON command is like this:

echo on

Now let's move to the batch file. First, if you're using Windows, open a DOS prompt. To make a batch program to load a program called test.bat, type this:

edit test.bat

Then type:

@echo off
cls
echo Hi, my name is %1
pause
echo This is the contents of this batch file:
pause
type test.bat
Then save it in a file called test.bat. The "%1" allows you to add data to your batch file from the command line. Whatever you type after the batch filename at the dos prompt will replace the %1.

At DOS prompt, type

myname Tom

Now you can use your name here and your program will start.

From the above, you know that batch files are created using a text editor such as EDIT. You may use a word processor but you must remember to save the file as text or ASCII text, since normal word processing files contain special character codes which won't be recognized by DOS and with its extension .bat

Now let's go a bit further about batch file programming.

Program Control

Normally, all commands in the batch file will be executed in the order in which they appear in the file. This is called a sequence. Sometimes, there are circumstances in which you would like to carry out commands in a different order or carry out a single command repeatedly. Try to copy the following code into a batch file and save it with the name test.bat then run it.

----------------------------------
echo off
REM print ray all over the screen
:start
echo ray
goto start
REM end of program
----------------------------------
Note:

1. To stop the program from running, you need to press Ctrl+C keys.

2. REM is short form for remark.

What happened? Your program should have repeatedly printed a name on the screen.

The key command is called GOTO. It transfers program control to a place in the batch file that you specify. In this case, we tell the program to go to a line that begins with a label called :start. Labels don't actually do anything in themeselves, they just act as a point of reference in a program. You can call labels almost anything you like, except you must ensure that they always begin with a colon ':'.

Every time the program reaches the goto command, it is told to go back to the start and repeat the echo command again. Thus, this program never terminates and will continue until you interrupt it.

Instead of printing steve every time you run the program, you could ask the user which word they wanted printed. To do this you need to make use of parameters (%1,%2..etc), in much the same way you did in the above.

-------------------------------------
echo off
REM ask user for what word to print
:start
echo %1
goto start
REM end of program
-------------------------------------
save the file with the name test2.bat and then run it like this

test2 anyword

Now let's have a look at some other batch file programming commands:

Command FOR...IN...DO

The format of the FOR command is

FOR variable IN (argumentlist) DO command

This is a repetition construct which will execute 'command' a number of times, depending on what's in the argument list. Suppose we have a list of names to process.

The following is an example:

----------------------------------------------
echo off
Rem command that prints out a list of names
FOR %%a IN (Ray Bob Tom Mary Joe) DO echo %%a 
----------------------------------------------
In this case the loop will execute the echo command 5 times becuase there are 5 items in the argument list. See how we are able to use the variable %%a as a substitute for each of the names? %%a is a variable that can take the value of a number of characters. When the echo command is executed, the value of %%a is printed out.

We aren't confined to just simple character strings either. We could use wildcard characters or user definable parameters. This command will print out a list of the names of text files stored in the current directory.

The following is an example:

--------------------------------
echo off
FOR %%a IN (*.txt) DO echo %%a
--------------------------------
Command IF

The IF command is used in batch files to test whether a condition is met or not. This allows the batch file to perform a particular action only if a particular condition is met. There are several different variations of the IF command: IF EXIST, IF ERRORLEVEL, and IF x == y (yes! it does use two equal signs!).

This program shows you how the IF command works

--------------------------------------------------
ECHO OFF 
REM call the batch file exists.bat 
REM check whether a file called 'test.txt' exists 
IF EXIST test.txt GOTO :success 
IF NOT EXIST test.txt GOTO :error 

:success 
ECHO file test.txt exists 
GOTO :end 

:error 
ECHO Error - can't find the test.txt file 
GOTO :end 

:end 
REM do nothing. This is just the end of the file 
--------------------------------------------------
If you don't have a file called test.txt in your current directory, the message 'Error - can't find the text.txt file' should be printed.

You can create a file called test.txt and run the batch file again. Now see what happens?

IF EXIST and IF NOT EXIST are the key commands. They test whether the file named test.txt exists and transfer control (using GOTO) to the appropriate error message.

Input command

We have seen that parameters are one way of getting input from the user. But here we look at some more flexible ways. We might, for example, want the user to choose an option from a menu of options, or answer a question (e.g. Are you sure you want to delete this file [y,n] ?).

Here's an example of a safer version of the DEL command which asks for confirmation before deleting a file.

-----------------------------------------------
REM SAFEDEL.BAT 
REM choice gives you 2 options - either y or n 

CHOICE/C:yn Are you sure you want to delete %1 
IF ERRORLEVEL 2 GOTO :no 
IF ERRORLEVEL 1 GOTO :yes 

:yes 
DEL %a 
GOTO :end 

:no
echo file %1 not deleted 
GOTO :end 
:end 
-----------------------------------------------
Of course, using DEL /P is a much better way of using DEL safely but the point is to demonstrate how you might use the CHOICE commands as a means of getting response from the user.

If you want to have more choices, you can use the following code:

------------------------------
CHOICE/C:abcd choose a letter 
IF ERRORLEVEL 4 GOTO choice_d 
IF ERRORLEVEL 3 GOTO choice_c 
IF ERRORLEVEL 2 GOTO choice_b 
IF ERRORLEVEL 1 GOTO choice_a 
------------------------------
Note: the syntax and order of the statements. This is extremely important! The first line lets you specify which keys you want the user to choose from.

Command SHIFT

The SHIFT command is possibly, at first, the most confusing batch file command. It needn't be. Simply, the SHIFT command increases the number of command-line parameters accessible by a batch file. Each time SHIFT is called, the value in the 1st parameter is discarded and replaced by the value of the 2nd parameter. The value in the 2nd parameter is replaced by the value in the 3rd parameter, etcetera, etcetera, until the 9th parameter is replaced by the previously unavailable 10th parameter.

The SHIFT command provides considerable power to batch files. It allows a batch file to operate on an unknown number of parameters. The SHIFT command is often used in situations where an operation needs to be performed on several files or directories.

The following example displays the contents of the files typed after the batch file name one page at a time.

------------------------
:LOOP
TYPE %1 | MORE
SHIFT
IF "%1" == "" GOTO END
GOTO LOOP
:END
------------------------
Command CALL

The CALL command is used to run another batch file from within a batch file. Execution of the current batch file is paused and the called batch file is run. After the called batch file has finished running, the original batch file is resumed at the line after the CALL statement.

Note: If another batch file is run from within a batch file by simply using its name, after the called batch file finishes executing, control is returned to the Command Line, NOT the original batch file. The Syntax is as follows:

CALL batchfilename [parameters] [switches]

The CALL command is used to provide modularity to batch files. Batch files can be re-used effortlessly if they are written with modularity in mind. Let's see an example as follows:

----------------------------
IF %1 == A: CALL FLOPPY.BAT 
----------------------------
File Redirection

Normally, DOS assumes all input commands come from the keyboard, and prints out the results on the screen (usually called standard input/output). But this does not always have to be the case. You can use the input direction operator '>' to send output to a file rather than the screen. The following is an example:

DIR A: > catalogue

The above will put the results of the DIR command into a file called catalogue, thus giving you a file which describes the contents of your floppy disk.

You can also take input from a file using the '<' rather than the keyboard but this is more unusual. For one thing, batch files perform this operation automatically without having to use the operator.

Input/Output direction don't look especially useful at this point. However, you may find they become more useful when we get on to using UNIX.

Filters

Filters are used to process data in some way. One such filter is called MORE. You can use it (e.g.) to display long files one screen at a time:

MORE < test.txt

Note: how MORE makes use of the redirection operator.

Another filter is FIND which looks for occurrences of strings in files.

FIND "this" MYFILE.TXT

In sum, the tutorial gives you only the basic concept of windows batch file programming. If you want to learn more, you need to do more research.

©1994 - 2010 Edusoftmax Inc. All rights reserved. Questions? Comments?    Visitors: