1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Making BATCH files [.bat]

Discussion in 'Code Snippets and Tutorials' started by .aId, Jan 8, 2007.

Thread Status:
Not open for further replies.
  1. .aId

    .aId Level I

    Joined:
    Nov 17, 2006
    Messages:
    119
    Likes Received:
    0
    Location:
    LoserVille
    This Guide Was Write in WORD, and then copy here.
    Try this, but have caution, batch can be so much DESTRUCTIVE. I dont have any responsability.

    PART 1

    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:

    Code (Text):
    1. copy [source] [destination]
    2.  
    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:

    Code (Text):
    1. 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:

    Code (Text):
    1. del [filename]
    2.  
    For example, if you wanted to delete a file called a:\happy.txt you would type this:

    Code (Text):
    1. del a:\neofriendsrlz.txt
    The CLS command clears the screen. This is the syntax:

    Code (Text):
    1. cls
    2.  
    PAUSE is a command that stops the program and prompts you to "Press any key to continue." The syntax is:

    Code (Text):
    1. pause
    2.  
    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:

    Code (Text):
    1. @echo off
    2.  
    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:

    Code (Text):
    1. echo on
    2.  
    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

    Code (Text):
    1. edit myname.bat
    2.  
    Then type:

    Code (Text):
    1. @echo off
    2. cls
    3. echo Hi, my name is %1
    4. pause
    5. echo This is the contents of this batch file:
    6. pause
    7. type myname.bat
    8.  
    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

    Code (Text):
    1. myname aId
    2.  
    ( 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.
     
  2. .aId

    .aId Level I

    Joined:
    Nov 17, 2006
    Messages:
    119
    Likes Received:
    0
    Location:
    LoserVille
    PART 2

    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.

    Code (Text):
    1. echo off
    2. REM print steve all over the screen (put your own name in instead)
    3. :start
    4. echo steve
    5. goto start
    6. REM end of program
    7.  
    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.

    Code (Text):
    1. echo off
    2. REM ask user for what word to print
    3. :start
    4. echo %1
    5. goto start
    6. REM end of program
    7.  
    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.


    Code (Text):
    1. echo off
    2. Rem command that prints out a list of names
    3. FOR %%a IN (Andrew Bob Carol Daisy Ellen) DO echo %%a
    4.  
    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.

    Code (Text):
    1. echo off
    2. FOR %%a IN (*.txt) DO echo %%a
    3.  
    IF
    This program demonstrates how the IF command works

    Code (Text):
    1. ECHO OFF
    2. REM call the batch file exists.bat
    3. REM check whether a file called 'test.txt' exists
    4. IF EXIST test.txt GOTO :success
    5. IF NOT EXIST test.txt GOTO :error
    6.  
    7. :success
    8. ECHO file test.txt exists
    9. GOTO :end
    10.  
    11. :error
    12. ECHO Error - can't find the test.txt file
    13. GOTO :end
    14.  
    15. :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.
     
  3. .aId

    .aId Level I

    Joined:
    Nov 17, 2006
    Messages:
    119
    Likes Received:
    0
    Location:
    LoserVille
    PART 3

    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.

    Code (Text):
    1. REM SAFEDEL.BAT
    REM choice gives you 2 options in this case - either y or n

    Code (Text):
    1. CHOICE/C:yn Are you sure you want to delete %1
    2. IF ERRORLEVEL 2 GOTO :no
    3. IF ERRORLEVEL 1 GOTO :yes
    4.  
    5. :yes
    6. DEL %a
    7. GOTO :end
    8.  
    9. :no
    10. echo file %1 not deleted
    11. GOTO :end
    12. :end
    13.  
    14.  
    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:



    Code (Text):
    1. CHOICE/C:abcd choose a letter
    2. IF ERRORLEVEL 4 GOTO choice_d
    3. IF ERRORLEVEL 3 GOTO choice_c
    4. IF ERRORLEVEL 2 GOTO choice_b
    5. 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.


    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,

    Code (Text):
    1. 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:

    Code (Text):
    1. 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




    CONGRATUILATION, YOUR LEARN BATCH :)

    +REP IS APRECIATED :)
     
  4. expon

    expon Administrator
    Staff Member

    Joined:
    Oct 30, 2006
    Messages:
    1,393
    Likes Received:
    56
    Location:
    UK
Thread Status:
Not open for further replies.