Page 1 of 1

Batch Tutorial Part 1 Covers all the basics Rate Topic: ***** 1 Votes

#1 polymath  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 52
  • View blog
  • Posts: 670
  • Joined: 04-April 08

Posted 18 June 2008 - 07:14 PM

*
POPULAR

I find that Batch Files can be just as effective as other programming languages for simple tasks in the console window. This tutorial will teach you the basics of this simple and extremely easy-to-learn pseudo-language.

First, a quick reference site for batch files is computerhope.com AND if you use this site, be aware that all of the MS-DOS commands can be used in batch files. Also, you can go into command prompt and type the command followed by /? and it should show you the syntax and a quick overview of the command.

For this tutorial, I am assuming that you have little-to-no experience with batch files, and some experience with windows (windows explore, copy-paste, etc. basic stuff).

That said, lets get started.

Creating a Batch File:
Batch files are easy to create and can be done using notepad quite easily. When you save a batch file, specify the .bat extension, and check to make sure that the save-as-type is set to all files. Or, you can rename .txt files, though its better practice to initially save them as batch files. That was easy. If only I had a staples button...

Editing Batch Files:
Obviously, you can't just double-click on the batch file and edit it. Since batch is run through DOS (the command prompt), it doesn't require compiling, so double-clicking on it will run the program. Instead, right-click and go to edit. This will open up notepad for you with the file.

Running Batch Files:
Treat just like an exe file, double-click.

And Now For the Fun Part-Coding, Commands, Etc.:

First off, REM is the comment command. Actually, REM is a command which does nothing, technically speaking, and takes arguments that do nothing. Yes, even the comment is a command that is interpreted by the computer. Thats why there are no block comments in batch file programming. I use it throughout.

The first command you should know is the @ECHO OFF command. Note that no DOS commands are case sensitive, and batch files do not require semicolons. By default, the console will display all of the lines of code as they execute and then the result. Most of the time, the source code is unnecessary to the user, creates clutter, and in other cases gives away security and such. So, make this the first line of code in most of your programs. Next, we can learn the ECHO command. This prints out anything we want it, and there are no string literals in batch, so we just type what we want outputted, like ECHO Hello World. Echo with a period after it is a blank line. So, a "hello world" program would look like:
@ECHO OFF
ECHO Hello World!



Next, we should learn the pause command. Any veteran programmer will know that in the above code, the window will open, execute, and then close abruptly before the user can absorb the information. So we use the pause command to hold the window open. Simply typing "pause" will output "Press any key to continue... ", which is good, though if you don't wish to display that message, and use your own, you can echo your message and then type pause>null to wait for the user to press a key. So we could use either:
@ECHO OFF
ECHO Hello World!
ECHO.
pause



or

@ECHO OFF
ECHO Hello World!
ECHO.
ECHO Press any key to exit. 
REM Notice the space in the echo above.  It looks better, and will become important for other uses later on
pause>null



Though I would choose the second one, more specific to the situation, continuing isn't the same as exiting (may cause confusion), etcetera.

The next command we will be using is the START command. This is used to run an external executable. So if i wanted to run helloworld.bat, and it was in the same folder as the bat file we're working with, we can use this:
START helloworld.bat


START can also be used to start explore, you know, to look at files. So if I didn't want to go through my network places to find a file, you could use:
START \\networkedcomputername\sharedfolder


or if you wanted to start www.google.com:
START www.google.com


This will open google in your default html browser.

The interesting thing about the first example, to start helloworld.bat, the syntax of DOS allows us to leave out start when running batch files. As a matter of fact, many pre-existing DOS commands are .exe or .bat files in the system32 folder(which is in the PATH variable, so we don't need to include the full path when starting it.). So, for out purposes, START command.exe and command are all equivalent in cmd.exe/cmd.com's eyes (Most of the commands in this tutorial are internal commands, meaning that they do not have a .exe equivilant, but i'll tell you when there is an external command, which does have a .exe form). Any modifier is an argument. Even something as basic as the echo command is really a precompiled exe file ready for your use. This easily allows you to create your own commands. Instead of START helloworld.bat we could simply type helloworld as if it was our own command to work with! If you're feeling really ambitious, you can even dump your commands into the system folders and add commands that can be used in any batch file (though changing system files can really mess with your computer if you do not know what you are doing, I do not advise this for novices).

A very handy command (especially when on a LAN) is the shutdown command (Also our first external command, this one actually works for shutdown.exe). This allows you to shutdown the computer (wow, didn't see that one coming). NOTE: The switches for this one can be used with '/' in all windows operating systems, but XP says you have to use '-', which is false. Use '/' because it works in XP, Vista, and Win9?. If you want to shutdown your computer, you just type shutdown /s. There are a bunch of other useful switches, but this is just the basics. One more switch, the /m switch. With this switch you can shutdown any computer over the network. Now, here is where this comes to be useful. Imagine you are the IT person of a humogous firm, and many lazy workers tend to leave their computers on after they leave. In addition, durring potential power surges, you have hundreds of thousands of dollars of sensitive electronic equipment on the line! You need to shutdown all of the computers in the building at the end of the day, without walking through every floor and clicking the off button. All you need to do is make a .bat file with the code:
@ECHO OFF
ECHO Shutting down all networked computers.  Please wait...
SHUTDOWN /s /m \\*
REM The above line actually shuts down all the computers on the network, using the * wildcard
SHUTDOWN /a
REM That line keeps the shutdown from affecting your computer, /a is the abort switch
ECHO Shutdown Finished.  Press any key to exit. 
pause>nul


Here we start to see where batch files actually start to work to accomplish tasks. A side note on SHUTDOWN: I have actually never shut down a computer over my network, I'm too lazy to give myself permission to do that :) .

Another command that actually gets a lot of work done is the copy duo: COPY and XCOPY. Copy has a few switches, mostly just for basic ctrl-c, ctrl-v modification. Not much other than: COPY source destination Except for the -Y switch (which goes before the source) and overrides the "Do you wish to replace this file of the same name?" dialog. A neat trick with copy is that it can append files of the same encoding (ANSII/ASCII, UTF, BIN, HEX, etc). If file1.txt contained "hello", file2.txt " ", file3.txt "world", and file4.txt was blank, we could enter:
COPY file1.txt + file2.txt + file3.txt file4.txt


Now, what if you need more functionality, like copying entire directories over, instead of one or two files (copy can only have filenames as the source and either filenames or directories as the destination). Enter XCOPY, the magic do-it-all copy command on steroids, HGH, and several illegal narcotics (Speed, PCP for example). XCOPY is incredibly functional, but that comes at a high price for syntax. Whenever you use XCOPY, I would suggest consulting the syntax reference for the myriad switches, modifiers, and arguments (There are almost 30 possible args for this function, and they should be in the correct order.). This command allows for greater use without user input. It can automatically override dialogs, copy or delete readonly and archived files, copy (or not copy) subdirectories, copy the directory structure without copying any files, copy encrypted files, choose whether or not to display filenames when they are copied, copy system and hidden files, discriminate against and/or copy file attributes, exclude files, copy authorship, and the ability to only copy files which do(n't) already exist in the target directory. Whew. Don't make me go over the syntax, just do XCOPY /?. Since there's no way DOS would already have this installed inside, Microsoft made it an external command (unlike copy, which is internal). Just thinking of all the code that would be required for all of that makes me sick. To make a batch file that does the same thing would take multiple pages worth of code... bleh...

A little code snippet using XCOPY to make a game installer for Axis and Allies (the computer game, I made this a long time ago and found it as I was digging through archived files to delete, thought it would make a good example) will be provided near the end (you need to know three or so more commands first). The file includes a directory containing all of the DirectX data and Program Files needed to run the game, called setup files. It also has what I call a TUI, or textual user interface (GUIs are for squares who have no life except sitting there programming really long programs in confusing APIs that have nothing to do with the base language, but then, squares are the people who get a lot of $ :) I make GUIs every once and a while, but don't find it an enjoyable experience).

The above commands are great for making little utilities to do commonly used tasks for you, but don't have much in the form of user input. In that they are limited. Batch Files are EXTREMELY Weakly-Typed, meaning that there are no data types, and that you only get an error when you try to multiply an integer by a string! Variables in Batch are just like variables in Algebra, but with one key difference: Batch Files use variables as strings which replace themselves by their value. For example, variables in Batch are created using the SET command, which has two optional switches:
REM Some code...
SET a=2
REM That sets A to the string of two.
REM Alternatively, you can use the /A switch to indicate an expression.
REM And if you want the user to imput the value in XP or later:
REM Notice I've put a space at the end
SET /P a=Please input a number to store to a: 
REM Otherwise, you'd be typing right next to the colon.  The prompt string ("Please...a:") can be empty


This basically sets some values to the command. To reference the value we put it in %variable%. Or, if you want your program run from the command line (like if your creating your own command, such as helloworld.bat), the first argument would be %1, the second %2, and so on. Note, number variables cannot be set once they have been set as arguments. Also, notice how environment variables you create have the variable names enclosed by %s, while arguments only have a leading % and then the argument number. The nice thing about batch variables is how they work. Whenever the command prompt sees a variable, it simply replaces it with the variable. This lets us easily output and concatenate strings and numbers together without any type casting. An example of variable use and user input in a batch file test.bat called from commandline with one arg:
@ECHO OFF
ECHO To call this program you typed test.bat %1
ECHO Your argument was %1.
SET /P userin=Please type a value: 
ECHO The value you typed was: %userin%
ECHO Press any key to exit...
PAUSE>nul



OUTPUT:


C:\>test.bat helloworld
To call this program you typed test.bat helloworld
Your argument was helloworld
Please type a value: hi
The value you typed was: hi
Press any key to exit...
x
C:\>


You can see where we run into problems, though, with the weak typing:

CODE:
@ECHO OFF
REM Call this with two args, and it will add them.
REM File Name:demonstrate.bat
SET a=%1+%2
ECHO %a%
[code]

What if I typed [inline]demonstrate.bat 1 hi[/inline]?  The program would try to add hi and 1.  See, when it simply replaces the strings, it will replace %1 with the arg i typed, 1.  So, a will actually be 1+%2.  But no calculator can add 1 and hi.  It would work fine if i had the args 1 and 2.  It would echo 3, if you followed along.  So you must be careful.  However, you can prevent problems like this using the IF command and the errorlevel variable.  IF is another internal command whose syntax goes like this (if it is in [] it is optional): [inline]IF [/I] [NOT] [EXIST] CONDITION Expression [ELSE Expression2][/inline].  We can use () to set it off, too, which is especially important when you consider that the ECHO command must be terminated by a newline.  The /I switch is for evaluating a variable to a string, and you want it to be non-case-sensetive.  The NOT argument is obvious, it reverses the truth/false of the condition.  EXIST means that CONDITION is actually the name of a file.  Then, if the file actually exists it will return true, and if there is no file of that name, it will return false.  CONDITION is what is to be evaluated.  Expression is the expression to be evaluated if CONDITION is true (or false, if using the argument NOT).  ELSE Expression2 is executed if CONDITION is false (or true, if using NOT).  IF can be used to check for errors.  For example, 0 generally means that the command was successful.  Before I show you an example, I have one more command to tell you.  This is the goto %label% command.  You can set a label anywhere in the program, and then you can jump to it using the goto command.  To create a label named 1 you would type [inline]:1[/inline] on its own line anywhere in the program.  Then, to cause the program to go to that line, you would type [inline]goto 1[/inline].  You can also use a variable, like [inline]goto %userin%[/inline].  Since we know that it would just replace userin with the variable's value, regardless of its surroundings, it could goto any label it wants, from :exit to :hdlshfa;lkdhsglkxchsdlk to :3 .  Hope I haven't given you too much to think about.  Here's a example of some of what we've learned so far.  This is good ol' demonstrate.bat again:

CODE:
[code]
@ECHO OFF
REM Call this with two args, and it will add them.
SET a=%1+%2
goto errors-%errorlevel%
:errors-0
REM This is if it was successful
ECHO %a%
goto exit
:errors-1
REM this is if it had an error:
ECHO Errors occured.
goto exit
REM GUESS WHAT, THIS REM WILL NEVER EVER BE READ!  IT WILL BE SKIPPED OVER BY THE GOTOS
:exit
ECHO.
ECHO press any key to exit.
PAUSE>nul



Alternatively:
@ECHO OFF
REM Call this with two args, and it will add them.
SET a=%1+%2
IF %ERRORLEVEL%==0 (goto errors-0) ELSE (goto errors-1)
REM Instead of using goto with the variable, this uses an IF-ELSE structure
:errors-0
REM This is if it was successful
ECHO %a%
goto exit
:errors-1
REM this is if it had an error:
ECHO Errors occurred.
goto exit
REM GUESS WHAT, THIS REM WILL NEVER EVER BE READ!  IT WILL BE SKIPPED OVER BY THE GOTOS
:exit
ECHO.
ECHO press any key to exit.
PAUSE>nul



Both will do pretty much the same thing. Note, that you can break up if-else among multiple lines if you're using echo or sommat:
IF CONDITION (
ECHO X
) ELSE (
ECHO Y
)


This will work, since the IF and the ELSE are on the same "line" (the command prompt automatically puts all of the commands on one line for the above, however, it won't echo the else if you have it move the result up into the parenthases. That code will work, but if it was on one line, it would echo: X) ELSE (ECHO Y), clearly not what was intended. ECHO needs to be on its own line. This won't work:
IF CONDITION (
ECHO X
)
ELSE
(
ECHO Y
)


More readable, but this time the IF and ELSE are interpreted as seperate commands, and since ELSE is not a command, but an argument, it generates an error. As a side note, a common use of labels in batch is to section off areas of code to create pseudo-functions, and jump to the function, and then back into the line after it was called. More on that in the final snippet.

Lastly, but not least, loops:

These are relatively simple. They evaluate while a certian condition is true. This is a trick question, however. FOR is an incredibly complex command I will not go over in this tutorial, simply because it is out of its scope. (for you java folks its more like the FOR EACH/IN command, but not exactly) Maybe in a later one, huh? I can't cover every command. :( WHILE, however, doesn't even exist. We can make a simple loop, however, using gotos:
IF NOT CONDITION (goto endloop)
REM The above will skip the loop if the condition isn't met in the first place.  Remove if you want do...while
:loop
REM Insert commands...
REM If, after all commands are executed, the condition is still true, the loop will restart in the line below.  Otherwise, it will continue on.
IF CONDITION (goto loop)
:endloop



This is the same as this code in C++:

while(CONDITION) {
//Insert Commands...
}


The two if statements and the labels replace the loop structure.

Now, i promised you some challenge code, eh? Well, here you go. Its not documented (i removed it all) so you could try to figure out what it was doing by yourselves. It uses only commands you have learned in this tutorial. The purpose of this tutorial was to get you started, so that with a couple of syntax lookups, and a few googles, you could figure out either A> how a program was working and what it was doing (structure) or B> you could design your own code. If you can figure this out, you're golden. Thanks for reading my tutorial.

@ECHO OFF
ECHO Axis and Allies Installer and Player
ECHO.
ECHO Windows Version 1.0
ECHO.
:RunInstall
set /p run=Play Game or Install (play/install):  
IF /I %run%==play (START "\Autorun.exe") ELSE (IF /I %run%==install (GOTO INSTALLER) ELSE (GOTO INVLD))
:INSTALLER
:USERIN
set /p userin=Do you wish to install Axis and Allies? (y/n):  
ECHO.
IF /I %userin%==y (GOTO INSTALL) ELSE (IF /I %userin%==n (ECHO You chose no) ELSE (GOTO INVALID))
ECHO.
:EXIT
ECHO Press any key to exit
pause>nul
Exit
:INVLD
ECHO Invalid Response.  Please type only "play" or "install".
ECHO.
GOTO RunInstall
:INVALID
ECHO Invalid response.  Please try again.
ECHO.
GOTO USERIN
:INSTALL
ECHO You chose yes
ECHO.
ECHO Deleting existing files (if applicable)...
ECHO.
IF EXIST "C:\Program Files\Axis and Allies\AA.exe" DELTREE /Y "C:\Program Files\Axis and Allies"
ECHO Installing new files...
XCOPY \setup_files "C:\Program Files" /E /I /Q /R /Y
ECHO.
ECHO Finished with setup.
ECHO.
GOTO EXIT


Its not that long or complicated, is it!? Enjoy! Happy Coding!

A closing note: In other tutorials you may see comments as a line with :: in front of it. This creates a label that is invalid, and thus, is not interpreted. It is invalid and non standards-compliant to comment your code in this way. Though it may run slightly faster because it is skipping the line of code instead of executing an empty function with REM, it is much safer to use traditional comments. In the end, its personal preference. Though I think speed (and really, not that much, one line of code is all that's skipped) is outweighed by being standards-compliant, and having a lower chance of bugs in my program (occasionally, a double colon will fail and wreck the program). That is all. Just be wary, Batch programmers and DOS Hackers (who of course use a lot of .bat files) like to break the rules :)

Commands/Topics to be covered in my next tutorial:
FOR
SUBST
DIR
CALL
PATH
PING
DEL
DELTREE
BATCH-TO-EXE CONVERSION
AND EVEN MORE!!!

EDIT1: Quick error/BBCode corrections

This post has been edited by polymath: 19 June 2008 - 07:22 AM


Is This A Good Question/Topic? 6
  • +

Replies To: Batch Tutorial Part 1

#2 jacobjordan  Icon User is offline

  • class Me : Perfection
  • member icon

Reputation: 113
  • View blog
  • Posts: 1,499
  • Joined: 11-June 08

Posted 09 July 2008 - 05:37 PM

Great tutorial. :^:
Always wanted to know how to use a batch file, that way i can hack my school computers with them. JUST KIDDING, but i did always wonder how to use a batch file. Can't wait for part 2.
Was This Post Helpful? 0
  • +
  • -

#3 born2c0de  Icon User is offline

  • printf("I'm a %XR",195936478);
  • member icon

Reputation: 180
  • View blog
  • Posts: 4,667
  • Joined: 26-November 04

Posted 10 July 2008 - 12:57 AM

Good Job polymath :^:
Was This Post Helpful? 0
  • +
  • -

#4 chatghosty  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 3
  • Joined: 29-October 08

Posted 29 October 2008 - 08:09 PM

I just found this out. But you used a SET command. And SET Command only work on windows XP. It would not work on Vista nor 98. Correct me if im wroung. :pirate:
Was This Post Helpful? 0
  • +
  • -

#5 prabh  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 3
  • View blog
  • Posts: 381
  • Joined: 27-December 08

Posted 08 June 2009 - 01:01 PM

it is the best batch tutorial on internet
marvelous work man
keep it up
Was This Post Helpful? 0
  • +
  • -

#6 polymath  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 52
  • View blog
  • Posts: 670
  • Joined: 04-April 08

Posted 08 June 2009 - 03:38 PM

Quote

I just found this out. But you used a SET command. And SET Command only work on windows XP. It would not work on Vista nor 98. Correct me if im wroung. pirate.gif


Not to my knowledge... though the /p switch is fairly new... and i'm not sure about /a]

I'm writing Part II currently, even though i've migrated from Windows to Linux currently. I'll hope to include all of the commands i promised. This should provide a nice break from this ridiculously long C++ tutorial i'm writing :D
Was This Post Helpful? 0
  • +
  • -

#7 Microchip55  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 02-December 09

Posted 09 December 2009 - 06:24 PM

View Postchatghosty, on 29 Oct, 2008 - 07:09 PM, said:

I just found this out. But you used a SET command. And SET Command only work on windows XP. It would not work on Vista nor 98. Correct me if im wroung. :pirate:


the set command WILL work on vista and may or may not work for the new windows 7 or 98 but I know set will work on vista because thats the OS I use and i use it on almost all my batch files.
Was This Post Helpful? 0
  • +
  • -

#8 cabinet  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 19-July 10

Posted 19 July 2010 - 12:24 PM

Could you make more TUT on BATCH Files, which is seriously lacking. Especially FOR,IF,GOTO cmd's. Some examples about variable and parameters would be great. These are the things which i have not yet understood.

Anyone who can help me here: Besides that the TUT was helpful,,pleaseeee make more TUTS.
Was This Post Helpful? 0
  • +
  • -

#9 Harlen  Icon User is offline

  • New D.I.C Head

Reputation: 4
  • View blog
  • Posts: 40
  • Joined: 08-February 10

Posted 10 August 2010 - 12:26 PM

View Postcabinet, on 19 July 2010 - 11:24 AM, said:

Could you make more TUT on BATCH Files, which is seriously lacking. Especially FOR,IF,GOTO cmd's. Some examples about variable and parameters would be great. These are the things which i have not yet understood.

Anyone who can help me here: Besides that the TUT was helpful,,pleaseeee make more TUTS.

Nice tutorial! Thanks!
Was This Post Helpful? 0
  • +
  • -

#10 y2161994  Icon User is offline

  • New D.I.C Head

Reputation: 15
  • View blog
  • Posts: 34
  • Joined: 08-July 11

Posted 17 July 2011 - 05:08 AM

Quote

Thanks brother.
Excellent.Will you create its cheat-code sheet so that I can download it & use while I m offline.

Was This Post Helpful? -3
  • +
  • -

#11 SuperLlama  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 04-November 12

Posted 04 November 2012 - 05:19 PM

Thank you so much!!
I am new to CMD and am trying to learn everything about it as I can. (Batch Files Included) I learned so much from this tutorial. Once again, THANKS!!!!!! Question: Is it possible to make a game on CMD? Will there be a second batch tutorial?

SuperLlama
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1