program batch

Making Batch Files

A batch file is a normal text file, no programming involved. You type DOS commands into a text file, each one on a seperate line. Then, you give the text file a .bat extension instead of a .txt extension. Now, when you double click the batch file(In Windows Explorer) or type its name at the DOS prompt, it will execute the commands.

First, we need to know some DOS commands. If you're a regular DOS user, you can skip this section and go to CREATING A BATCH PROGRAM. The main DOS commands we will use are copy, move, del, cls, and echo. The COPY command has this syntax:

copy [source] [destination]

In DOS help, the syntax is more complicated, but we don't need the advanced features for our batch files. The COPY command, obviously copies a file. For example, say I wanted to copy a:\readme.txt to a:\windows\help.txt. (By the way, this will also rename the file.) I would type this:

copy a:\readme.txt a:\windows\help.txt

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]

For example, if you wanted to delete a file called a:\happy.txt you would type this:

del a:\happy.txt

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

cls

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

pause

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

All good batch programs start with the @ECHO OFF command followed by CLS. Important!: 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 for the batch file! First, if you're using Windows, open a DOS prompt. To make a batch program to load a program called myname.bat, type this:

edit myname.bat

Then type:

@echo off
cls
echo Hi, my name is %1
pause
echo This is the contents of this batch file:
pause
type myname.bat

Then save it in a file called myname.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 Suzanne

( you can use your name here) and your program will start!

When you have completed this lab, make sure that I see it so that I can grade you. This is lab 3B.

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.



User Input

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 <>


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.

0 komentar:

Posting Komentar

!*Mohon Anda Memberi "Komen" Untuk penyempurnaan kedepan *!

Total Tayangan Halaman

Diberdayakan oleh Blogger.

Copyright © / TEKO

Template by : Urang-kurai / powered by :blogger