June 19th, 2002, 12:22 AM
Batch programing (Tips and Tricks)
I have made every effort to provide you with acurate and truthfull information, however, there may be errors found throught my tutorial. I take no responsibilities for any damages to your computer resulting from the use of the information provided herin. Use this information at your own risk. As a reminder, I do not premote the use of this information for ilegal activites, it is your responsibility for any actions resulting from inapropriate use of this information.
I assume you have used MS-DOS and are familiar with getting around in DOS. This includes a working knowledge of issueing commands, spesifing comand line arguments, getting help with commands and so on. Some experimenting with batch is in order since I do not fully document the entire batch language, I will provide you with the essentials to get you started but in no way once so ever is this a complete guide to batch. Besides it sais tips and tricks not the entire language.
Seeing how many tutorials can be found all over the internet, my goal is to produce unique, origional tutorials while at the same time pay close atention to quality and content. Assumeing DOS tutorials are wide spead, I figured a tutorial on batch programing, introduceing potential tricks to be used in batch programing would be well suited. So this tutorial is to introduce you to the world of batch programing, but at the same time provide you with some tips and tricks. But why would someone want to program with batch when there are so many programing languages out there like C, C++, Python, Java and more? Well as you are problably aware, difernt languages are more suited for one task then others. If you were makeing a CGI script to run on a web server, perl would problably be your choice rrather then useing C or some other language. At the same time, if you want to write quick small utilities for windows to load at boot time, batch may very well be your answer. So what are we waiting for lets dive in!
If you want to learn how to change the colors of your color monitor with batch skip ahead to the end of this tutorial, if not cary on.
The batch language itself is pritty simple, fist off all our batch source code is writen in pure ASCII text format, and saved with the extension .bat. This can be acomplished with the use of a text editor such as notepad. A batch file is more or less a colection of DOS commands, as well as special batch spasific commands, plased sequentialy one on top of another. When the batch file is executed, the commands contained within are executed one by one as if you were typeing them in yourself. So why would you want to make a batch file? Well one example might be, you use a certian sequence of DOS commands every day when you start up your computer in the mourning and it would be nice if we did not have to type them in manualy. Now, in batch we may use all of the commands available to our version of DOS, plus an aditional set of batch spasific commands. I will list some common DOS commands but for a complete refernce pick up a good DOS book at your local library:
Attrib (view and change file artributes)
ChkDsk (check disk utilitiy)
Choice (present the user with a choice, default is yes or no)
Cls (clear the screen)
Copy (copy a file from one location to another)
Date (display and/or change system date)
Del (delete a file)
DelTree (delete a directory and all subdirectorys)
Dir (list the contents of a spesified direcotry)
DiskCopy (copy the contents of one disk to another)
Erase (same as del, refer to del)
Extract (extract one or more cabinet files [*.cab])
Exit (terminate and start new copy of command.com)
Find (locate a string in a file(s) )
Format (format a disk for use with MS-DOS)
Mode (controll links to computer perhipherals such as COM, LPT1..)
More (a pager, used to display information one screen at a time)
Move (move files or directorys from one location to another)
Prompt (change the display of the command prompt)
Set (modify, display or remove an enviroment variable)
Sort (sort alphanumericaly the lines of ASCII text from input)
Start (starts a Windows or dos program in a new parent window)
Time (disply or set the system time)
Type (type the contents of a file to standard output [monitor])
As mentioned, not only may you use any of the DOS commands suported by your version of DOS, you may also use batch spasific commands made for the purpose of batch file writeing:
REM (remark, set comments. Used for documenting or commenting)
ECHO (used to turn echoing on or off, as well can display an optional text message)
PAUSE (suspends execution for spesified time period)
FOR (execute a DOS command iteratively)
GOTO (causes execution to jump to a spesified line, used for program branching)
IF (conditional oporator used to execute a command only if condition is satisfied)
SHIFT (shifts the contents of the program parameters)
CALL (invokes a batch file, executable program or DOS command)
The above is certianly not a complete list of commands available to the batch programer but it is certianly enough to produce some funky utilities. I have not provided the Syt\ntax or how to use the commands, you should know how to get help on a command in DOS, but if you don't just launch DOS, type the command name followed by a space and /?. This will provide you with help. As well you can look in your local library for a DOS book, hint check your version of DOS with the VER command, or visit http://www3.sympatico.ca/rhwatson/dos7/ and look up the command you are interested in. So what is the format of a batch file, I mean, how do you write a batch file? Well, let me show you an example:
ECHO This program was created by ele5125
REM Move to C:\My Documents\ele5125, if not exist create!
IF NOT EXIST c:\mydocu~1\ele5125\ md c:\mydocu~1\ele5125
REM Copy files spesified in argument 1 to my directory
copy %1 c:\mydocu~1\ele5125\
So what does the above batch file do? Simple, the first line turns off echo, however because echo was not previously off it would normaly display echo off on our screen, so to prevent this we preceed it by a @. This tells it not to display the command as it is being executed. Now that we have echo off we do not need to use @ because nothing will be displayed unless spesified otherwise. Next we tell DOS to display This program was created by ele5125 on the screen. Finaly we get to use rem to make a comment, this is for opur purposes and is ignored by DOS. It is so we have an idea what the next line does, when we look over our code next week. It is simular to comments in C. Now, we have a if conditional statement, we are saying to execute the command cd c:\mydocu~1\ele5125 only if c:\mydocu~1\ele5125 does not already exist. But what exactly is this c:\mydocu~1\ele5125 thingy? It is a directory on your hard drive. Actualy the directory is C:\My Documents\ele5125 but in DOS we cannot have long file names, we must stick to the 8.3 file nameing convention. So if our file name is greater then 8 characters long, we take the first 6 characters, ignoreing spaces, followed by a tilde ~ then the number 1. This makes My Documents mydocu~1 instead, thus satisfieing the 8 character limit. So apart from all that, it is clear as mud right? Good!
So if C:\My Documents\ele5125 does not exist we create it. Now we use the DOS cd command to chage the current directory to our newly created directory. Finaly we include another comment to make things easy to read, then move on to a copy command. Now if you look up the copy command it sais it copys a file from one location to another. So what in the hell is this %1 thingy? I am glad you asked. When we execute our program later we will spesify the program name (the name of the batch file) followed by a argument like so:
So assumeing we named out batch file batch1.bat our first argument is a:\*.* which just hapens to be a file spesification spesifieing all the files on my floppy disk, assumeing our floppy drive (FDD) is labled a:. So now in our batch file, to use this argument we refernce it by %1, why %1 and not %0? because %0 hapens to be our program name and %2 would be the second parametner if we gave it one. So we are copying from wherever the first argument sais so, to the new directory C:\My Documents\ele5125. The only major difernce between my batch file and the copy command is instead of copying to wherever we want, my batch program always copys to my own directory.
So that is all there is to writeing batch files, just use difernt combinations of DOS and batch file commands, type them line by line in sequence, name the file with a .bat extension and away we go. So why in the hell did I write this tutorial for you? Because now we can learn tricks with batch and we also have plenty of time for some examples to get you started. Remember, I do not document commands that I do not use, as well I do not document the arguments I don't use. So I strongly recomend you visit http://www3.sympatico.ca/rhwatson/dos7/ if you realy want to know how to use a command. Now for my tips and tricks:
Batch tips and tricks (and examples ):
Ok the first trick im going to tell you is how to compile a batch file into a executable file so you can pretend you did it in C . You can find a copy at http://nlsn.free.fr/batch-down/ it is very easy to use. to avoid any problems I sugest copying it to c:\windows\Command\ (in windows 9x). Next, lets get down to the meat of my tutorial.
**Batch Tips && Tricks**
#1 How to make a menu driven system:
Some of you may have woundered how you can make a simple menu in batch, well here is one way:
Set up a simple text file containing the menu text like so:
1) Do something...
2) Do something else...
3) Exit program
now save it with an extension txt, perhaps call it menu.txt, next create a separate batch file for each menu item named 1.bat, 2.bat, 3.bat excetra like so:
contents of 1.bat:
ECHO This batch file does something spesified in menu item 1
ECHO Do stuff..
contents of 3.bat:
REM return the prompt back to normal
And so on till you got a batch file for each menu item, you are not limited to batch files, they could be com or exe files. Now we make the main program:
contents of bat2.bat or whatever you called it:
prompt Enter your choice from the menu:
It is that simple, ok so how does it work? First you start by executeing our main program, in our example we called it batch2.bat it turns off echo being carful not to display anything. Then it types out the contents of menu.txt to the screen, this displays the menu. Next a prompt command is called to change out prompt from C:\> to Enter your choice from the menu: which makes more logical sence. So if we enter 1 and hit the enter button, it is the same as us typeing a command, now DOS will search the current direcotry for a program called 1, it finds 1.bat so it executes it. If you entered 2 the same type of thing happen, it finds 2.bat and executes it. Finaly if you choose 3 our 3.bat file will change the prompt back to normal and exit dos. Tada, that simple, there is your menu, now experiment! Yes thats wright, im not going to spoon feed you, you have to try things out and experiment.
#2 Getting beyond the 10 argument limit:
Now for our next trick, more then 10 command line arguemtns, exceeding the limit. but first we must understand what command line arguments are and how to use them. Command line arguments are extra information that you can give to the program on the command line. This is done by following the program name with the arguments like so:
program argument1 argument2 hello
here along with executeing the program named program, program recieves argument1 as %1 argument2 as %2 and so on. So now lets say we want to make a simple program, lets make the echo command:
contents of echo.bat:
So how does it work? Simple, it takes the first paramenter which hapens to be contained in %1 and it echos it to the screen or standard output. Here is an exaple DOS session with our new program:
C:\> echo hello
But what if we put hello world instead of hello? well it would only print hello because world would be in %2 not %1. Clear as mud?
So that is how we can use command line arguments, but we have a limitation, we may only have 10 arguments, but I want more!!!
Here is our solution. We can use the shift command to shift the arguments around, so that we one by one bring the 11th 12th 13th and so on arguments into the argument list and at the same time shift arguments 1 2 and 3 out. This sounds very confuseing so here is a example:
contents of the new and improved echo.bat:
ECHO %0 %1 %2 %3 %4 %5 %6 %7 %8 %9
ECHO %0 %1 %2 %3 %4 %5 %6 %7 %8 %9
ECHO %0 %1 %2 %3 %4 %5 %6 %7 %8 %9
Now let us start up DOS:
C:\> echo A B C D E F G H I J K
A B C D E F G H I
B C D E F G H I J
C D E F G H I J K
So what happened? well first we turn off echo, now we print all 10 arguments that we recieved, we have a limit of 10 so J and K are missing. Now we issue a shift command, this shifts all the arguments to the left one position, now we loose the first argument and a new one comes in at the right side. Thus eliminateing A and ataching a J to the end. We do another shift then print all 10 arguments and this time we loose B and gain K. So shift moves the arguments from right to left so we have access to the arguments that simply could not fit into all 10 variables. That is how we can get over the 10 argument limitation. Now of cource our echo will not print more then 12 arguments, so if we realy wanted our own echo we would use the for command. I will leave you with that thought to chew on. Lets cary on with our tips and tricks.
#3 How we can get input from our user:
Ever wounder how we can give the user one of those yes or no questions, if we echo the question how do we get a responce? Well today is your lucky day, the answer my friend is with the use of the choice command.
Here is the syntax for the choice command:
CHOICE prompts the user to select one of a specified set of keys in a batch program. It is the only Dos command that allows for controlled user input to a batch file.
CHOICE [text] [/C[:]choices] [/N] [/S] [/T[:]c,nn]
/C[:]choices The prompt - comprising a series of single alphanumeric characters corresponding to valid choices. The prompt is displayed as the characters, separated by commas, enclosed in brackets, and followed by a question mark. Default is YN
/N Stops the prompt from being displayed, although text is still shown and the choices keys are still valid.
/S Forces the choice keys to be case sensitive. By default they are not.
/T[:]c,nn Defaults choice to c after nn seconds.
c must exist; nn must be in the range 0 to 99.
text Text displayed before the prompt. Typically, text is used to expand on the subsequent prompt.
The above syntax came from http://www3.sympatico.ca/rhwatson/dos7/
So how do we use it? Let us take up an example:
REM ECHO OFF? Yea why not?
choice Would you like to turn on echo?
IF ERRORLEVEL 1 GOTO YES
IF ERRORLEVEL 2 GOTO NO
The first line turns off echo, nothing new here. Next we make a comment about the code that follows, again nothing new. Now we use our new found friend choice to present the user with a yes or no prompt, because it defaults to yes or no, we just spefify out text to display and leave it be. So how do we find out what our user inputerd? The answer is with error codes, depending on the key the user pushes, it will set a error level acording to the following:
0 (Choice was terminated with CTRL+C)
1 (The first choice was pressed)
n (The nth choice was pressed)
255 (There was an error)
So how do we test the error level? Simply use the IF statement like so:
IF [NOT] ERRORLEVEL number
where not is optional and number is the number of the error code to be tested for. We did this with IF ERRORLEVEL 1 GOTO YES and IF ERRORLEVEL 2 GOTO NO, the GOTO is a command that will tell the program to jump to the line labled whatever follows goto, in this case if it was a error level one indicateing our user chose yes we goto the line labled yes, if the user chose no it would be error level 2 therefor we would jump to line labled no. Lines that are lables start with : so :YES is our labled yes line and :NO is our labled no line, from there the program resumes normal sequential operation. We turn echo on or off acordingly then exit. Simple no? Again I am not here to spoon feed you, this is a tips and tricks tutorial, not full coverage of batch file programing.
#4 Tricks with your color monitor:
For this trick you will need to edit your config.sys file to include the following line:
DEVICE = ANSI.SYS
Now that we got that set up let us begin. We did this because we are going to be useing the ansi driver to controll our forground and background colors. Now normaly we would use the prompt command to display a difernt prompt, but it can however be used to send an escape code to the display. Now the ansi device driver that we loaded up in config.sys uses the controll sequence formate:
remembering of cource that we will send these controll commands with the use of the prompt command. But how exactly can we do this, how can we send commands to ansi.sys to change the screen colors? Well first we know the format to send controll sequences is ESC [#;....;#m and we send them with the prompt command. ESC is the abriviation for escape, and we know our parameters follow the [ between #; and ;# where # is the number corosponding to the code in our controll sequence. these numbers can be found in the table below:
0 All atributes off (normal white/black)
1 Bold on
4 Underscore (IBM Monocrome only)
5 Blink on
7 Reverse video on
8 Canceled on (visible)
30 Black forground
31 Red forground
32 Green forground
33 Yellow forground
34 Blue forground
35 Magenta forground
36 Cyan forground
37 White forground
40 Black background
41 Red background
42 Green background
43 Yellow background
44 Blue background
45 Magenta background
46 Cyan background
47 White background
So that means if i want to change the forground color to yelllow the code would be:
Now how can we use the prompt command to issue this controll sequence? Easy, with $e in place or ESC like so:
yes it realy is that simple, of cource after you made the change to config.sys you should reboot so the setting takes efect then you can play. Have fun!
I hope you have enjoyed these tips and tricks and I ceritanly hope they will come in handy. As well remember to check out the bat2exe so you can tell all your friends you are an 31337 C coder when realy you did it all in batch.
In snatches, they learn something of the wisdom
which is of good, and more of the mere knowledge which is of evil. But must I know what must not come, for I shale become those of knowledgedome. Peace~