MSc CBIS COMM57 Software Environments Tutorial 2- Batch Files
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 recognised by DOS. All batch files have a .BAT extension. You may run a batch file by just typing in its name at the DOS prompt and pressing return. It is not necessary to include the .BAT extension when running a batch file.
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 typing the listing below into a batch file, save it with the name rpt.bat then run it.
echo off REM print steve all over the screen (put your own name in instead) :start echo steve goto start REM end of program
Stop the program from running by pressingControl and C keys. 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 last tutorial.
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 rpt2.bat and then run it like this RPT2 anyword
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.
echo off Rem command that prints out a list of names FOR %%a IN (Andrew Bob Carol Daisy Ellen) 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 (see below). This command will print out a list of the names of text files stored in the current directory.
echo off FOR %%a IN (*.txt) DO echo %%a
Exercise Can you amend the above program to make it print out a list of text files AND a list of executable files (.EXE)?
Decision Making using IF This program demonstrates 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. Create a file called test.txt, and run the batch file again. 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. IF has several different uses. Type in the command if /? to get more information.
Exercise Amend the above program so that the user can choose any file they specify, rather than using text.txt all of the time.
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 in this case – 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. In this case we have only used 2 choices y or n, but you can have more. Your code would look something like this: 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.
Exercise Using the command you’ve just learned, write a batch file called winopt.bat that gives the user 4 choices: 1. Start Windows 2. Start DOSKEY 3. REturn to DOS Thus by simply entering a number from 1 to 3 the relevant command(s) should be invoked.
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. For example, DIR A: > catalogue 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. Why not try it now? 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 < FILE.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 Note that you must put quotes around your search string.
Exercise Can you write a batch file that uses find to search for strings in all text files in a complete directory (use a small directory to test this), and then puts its results in a separate file, rather than displaying them on the screen?
Finally… In this tutorial, we have only introduced the subject of batch files – complex commands can be created. For those that are interested, check out one of the many DOS manuals such as Microsoft’s or Peter Norton’s, for more detailed descriptions. DOS has a reasonably simple set of commands. Even so, it is possible to create full, working programs which are a lot more compact than the equivalent versions in some programming languages I could mention.