22858 total geeks with 3297 solutions
Recent challengers:
best bread maker
 Welcome, you are an anonymous user! [register] [login] Get a yourname@osix.net email address 

Articles

GEEK

User's box
Username:
Password:

Forgot password?
New account

Shoutbox
sefo
anilg, new comments are deleted automaticall y because of some abuse recently
anilg
this is plain wierd. I submitted comments twice to article 950, and they dont seem to be there. Something wrong with the comment code?
CodeX
shout-boxes in general are old + the staff thing happened to everyone after an issue 2 months ago
anilg
/me is no longer staff :(
anilg
Also, osix's shoutbox predated twitter. Heh.

Donate
Donate and help us fund new challenges
Donate!
Due Date: Jul 31
July Goal: $40.00
Gross: $0.00
Net Balance: $0.00
Left to go: $40.00
Contributors


News Feeds
The Register
UK.gov sticks to IE
6 cos it"s more
"cost effective",
innit
T-Mobile UK pumps
out the iPhone 4
Polaroid 300
instant print
camera
NatWest dumps O2
Money
YouTube ups video
time limit
Alleged expenses
fiddlers to face
justice
Nude trampolinist
bounces free from
court
Nexus One phone
rockets to 28,000ft
UK.gov drops £6m on
Google
Fake Firefox update
used to sling
scareware
Slashdot
British ISPs Favour
Well-Connected
Customers
"Bizarre"
Nanobubbles Found
In Strained
Graphene
1-in-1,000 Chance
of Asteroid Impact
In
...
2182?
2 Chinese ISPs
Serve 20% of World
Broadband Users
World"s Fastest
Hybrid OK"d For
Production
Sometimes It"s OK
To Steal My Games
Thermoelectrics
Could Let You Feel
the Heat In Games
KDE SC 4.7 May Use
OpenGL 3 For
Compositing
Perl 6, Early, With
Rakudo Star
Internal Costs Per
Gigabyte —
What Do You Pay?
Article viewer

DOS Batch File Programming



Written by:dimport
Published by:SAJChurchey
Published on:2003-06-21 07:19:46
Topic:Windows
Search OSI about Windows.More articles by dimport.
 viewed 90593 times send this article printer friendly

Digg this!
    Rate this article :
Is DOS dead? Is this or that or anything dead? Batch file programming is easy and fast, and can let you complete long and tedious tasks quickly without typing in hundreds of commands. Ready to learn something? Then read up on DOS BATCH FILE PROGRAMMING...



Think your a GEEK? Prove it on the Geek Challenges





Introduction to DOS Programming
DOS (disk operating system) is, like Windows, *nix, MacOS, an operating system. Like many other OSs it runs on a command line. The DOS command line looks like this:
Quote:
C:>

If you are not running DOS as your OS, but a flavor of Windows instead, it can be accessed by running 'command.com'. Command line operating systems must have, obviously, commands. These can be typed in to complete various tasks. For this tutorial, we will be saving lines of these commands in a BATCH file (.bat). When you run a batch file, the commands are executed. The scripts can be written in Notepad or any text editor. This is also what you will do when I provide examples in the tutorial. Then, save it as a .BAT file instead on .TXT. Now without further ado, the basic commands of a DOS Batch file...

Basic Commands
The first command that is taught in many programming languages is the command to print text to the screen. It is the command 'echo'. Lets see an example:
Quote:

C:>echo Hello, world!
Hello, world!
C:>
On the DOS command line, we typed the command 'echo' and then the text that we wanted to print to the screen. After it was done executing our command, it returned to the prompt (C:>). Another important command is 'cd'. This is the change directory command. At the command line (or in a .bat file) type 'cd' then the directory you would like to go to. For example:
The 'mkdir' command MaKes a DIRectory. Now to delete a directory, type 'del' then the directory. To list the contents of a particular directory, type 'dir' or 'dir armor' to list the contents of the directory 'armor'. Lets see this in action:
Quote:

C:>cd armor
C:armor>cd c:
C:>
(NOTE: the directory 'armor' must exist first. Lets see how to create it...)

C:>mkdir armor
C:>cd armor
C:armor>

Now we will put it all together into your very first batch file. Cut and copy the following into a text editor, save it as batch1.bat and then at the command line type 'batch1.bat' or 'batch1'.
Quote:

@ECHO OFF
echo Listing directory 'c:armor' contents
cd c:armor
dir

This batch file lists the contents of the directory 'c:armor' to the screen. We us the command '@echo off' to clean up the screen before we execute the rest of the code. Now for some more commands!

'rem' is a remark or comment in batch file programming. You can put it at the front of a line, and anything after that is not executed. This is just for your purposes, maybe writing your name and the date at the top. ':' is now also a remark command. You use it the same way as 'rem'.

'pause' is also an important command to know. It halts execution of the script until the user presses a key. This has a number of applications. It also print "Press any key to continue" to the screen.
'cls' is computer shorthand for CLear Screen. It clears the DOS screen of everything up until that command. Useful for cleaning up the screen before moving on to a new task.

'copy' copies a file to a new directory. The syntax is as follows: copy {file in original position} {new filename/position} .

That does it for your basic DOS commands. Play around with these are try to create your own simply batch files. Save them and run them often! After you have mastered these, move onto to 'Advanced Commands'. This is kind of a joke, because DOS batch file programming is
not advanced, and there isn't any difficult commands. These will simply allow you to create more useful programs by building on the ones we have just learned.

(More) Advanced Commands
Now we will learn something very important to creating useful batch scripts. We will use the '>' operator, allowing us to output to things other than the screen. Using this, we can print information to files. Lets see how this is done:

Quote:
@echo off
echo Hello, world > batchoutput.txt

There is one drawback to this, however, it deletes everything first, then outputs to the file. If we only want to add information, we use it's brother the '>>' operator, for example:

Quote:
@echo off
echo Hello, world > batchoutput.txt
echo Hello again, world >> batchoutput.txt

Time for a little quiz, if we ran both of these what would batchoutput.txt look like? Well, it would read: Hello, world Hello again, world .What if we did this:

Quote:
@echo off
echo Hello, world >> batchoutput.txt
echo Hello again, world > batchoutput.txt

Now batchoutput.txt would look like this: Hello again, world .This is because we deleted 'Hello, world' because we only used the '>' during the second echo command. Practice these techniques before moving onto our next section....

Parameters

A parameter can be a very powerful addition to your set of knowledge on DOS programming. This is a way of accepting input from the user. Parameters are signified by the %1 - %9 symbols. When the user types the name of your .bat file into the prompt, he/she can leave a space and type other information....called parameters. For example, the user wants to copy a file to one location from the directory he/she is currently at. To do this with your knowledge so far, you would need hundreds of seperate batch files. Now with parameters, the user can enter what file to copy and the location where the file will be copied easily. The code for this task is:

Quote:
@echo off
COPY %1 %2
ECHO file %1 copied to directory %2

Typing batch2 fun.txt c:fun would move the file fun.txt from the directory that holds batch2 and would place it in the directory c:fun as c:funfun.txt .Now, using parameters I would suggest you to practice and get comfortable manipulating and using them in your code. Once finished check out Control Flow.

Control Flow - Nonsequential Programming

Up until this point, you have been programming sequentially. This means that every command or statement that DOS has read, it has executed it in that order. Control Flow is controlling how your batch file will execute. Using this vital technique, you can go to different parts of the code, skip over parts, and even execute one part over and over. Lets start with something easy. Piping is when you can use multiple commands or statements on one line. This is done by using the | operator.
Quote:
IF EXIST batchoutput.txt RENAME batchoutput.txt
BatchProgrammingRules.txt | echo hi!

This code 'snippit' contains 3 new commands. It uses the piping technique, merging statements onto one line. Also, the 'IF EXIST' command does just what you think, IF the file EXISTS then execute the next command. The next command has to be on the same line. In this example, the next command is 'RENAME' which renames the first file to the second file. Lets look at the syntax:
Quote:
IF EXIST {filename} [COMMAND] {command arguments}

You can use almost any command with IF EXIST. The final command I will teach you in this tutorial is the GOTO command. Frowned upon in most programming languages, the GOTO statement 'goes to' a specified place in the code. To tell it where to go, you need to create
something like a 'tag'. You will understand with an example:
Quote:
IF EXIST helloworld.txt GOTO Hello
Hello: echo Hello, world!

The GOTO statement makes the execution jump to the tag specified. If the file helloworld.txt doesn't exist, the echo statement never gets executed.

The START and PAUSE CommandsThe START command starts a program. For instance, if you typed START notepad.exe the program notepad would be executed. This is useful for editing things like the registry and presenting the user with a program he or she can use. Another useful command, though hardly related to the START command, is PAUSE. This presents the user with a 'Press any key to continue' prompt. In Appendix A we will use this to ask the user to close the program after it is finished executing.

Hopefully you have learned something about DOS and programming. For all you 'elite' programmers scoffing at how I even consider batch programming, it is still useful and easy. I hope at least 1 person learned at least 1 thing. Thanks.

A work on a website Destroyed by Fire @ DestroyedbyFire.tk . Check it out. For any questions regarding this article e-mail me @ hushmail.

Appendix A
Quote:
@ECHO OFF
: a program that finds system files and saves them to a drive
specified and keeps a log as specified in the parameters.
ECHO [YOUR NAME HERE]'S SIMPLE BATCH FILE
:create a simple log
echo LOG STARTED >> %1
:the 1st parameter, %1 is the name & location of the log file
:the 2nd parameter, %2 is the directory you want to copy the recovered files to
:check if the files exist and copy them
IF EXIST c:windowssystem.ini COPY
c:windowssystem.ini %2
IF NOT EXIST c:windowssystem.ini echo ERROR
IN COPYING SYSTEM.INI >> %1
IF EXIST c:windowswin.ini COPY
c:windowswin.ini %2
IF NOT EXIST c:windowswin.ini echo ERROR IN
COPYING WIN.INI >> %1
echo All Done!
echo ALL EXISTING SYSTEM FILES COPIED. >> %1
echo LOG FINISHED >> %1
:clear the screen
PAUSE
CLS
EXIT


This article was originally written by armor

Did you like this article? There are hundreds more.

Comments:
Anonymous
2006-08-09 14:15:34
how open hidden .exe on .bat ( example john : @echo off john-386.exe test ) not hidden

answer ? thx
Anonymous
2006-12-04 07:41:13
How to assign a dynamic variable
Anonymous
2006-12-15 17:12:17
i have wrote 3 statments in my batch file..
but am unable to execute 3 stmt..
am starting a server before 3 stmt..after that am excuting 3 stmt which is in that server..

wht would be the problem..

if u can give solution am verymuch thankful to u.

thanks in advance..
my id sris4u@gmail.com
vasu
Anonymous
2007-02-28 11:17:29
Cool man, i just learned Dos and Batch file making in a litte time, thank's.
Anonymous
2007-03-04 16:17:27
BATCHING ROCKS!
Anonymous
2007-03-07 06:24:37
Very Very Helpfull
Anonymous
2007-04-14 20:25:28
How do/can you send text to a file with the '>' operator but not show the directory structure? (ex.
metallica\master of puppets
instead of
D:\rock\metallica\master of puppets)
?
Domuk
2007-04-14 20:33:37
I've no idea what you mean. Do you mean something like

echo Hello > "metallica\master of puppets.txt"


? Make a forum post and explain yourself.
Anonymous
2007-05-07 20:13:08
here is a bit technical, i am trying to create a batch file that searches for another batch file and runs it, what i have so far is dir for the batch file then > the results into another find.bat, running that batch file (find) where the results are from dir. it works, but under windows xp where you have something like c:\documents and settings, it doesnt uses the short naming system limited to 8 characters like c:\documen~\user\desktop. let me simplify this:

dir /b /s > find.bat
the results are: c:\documents and settings\user\desktop\find.bat

now when the batch file "find.bat is ran it does this:
"c:\documents" not found

my batch code so far:
echo off
cls
set t1=dir here.bat /s /b /4
%t1% > test.bat
test.bat

my question: is there any way to input the results into the batch file in the 8 character format?

cheers for any help

Mathew
Anonymous
2007-06-20 02:37:23
lets say i have a folder called c:\jpgs
and in it there are
abcd1.jpg
abcd2.jpg
abcd3.jpg

and i want to batch rename every one of them into

0001.jpg
0002.jpg
0003.jpg

how can i do that?

i remember from high school about setting a value for x=1
y=x+1
ren *.* y.*
next y

or something like that, please tell me.
bonlax
2007-07-06 09:46:05
REN C:\Fuckoff\abcd1.jpg<space>Stupid.jpg

bonlax
2007-07-06 09:48:57
here is the smple step's men..
open the dir where your jpg save then right click,choose rename..OK?
what a simple answer...
Anonymous
2007-07-11 07:44:08
@ jpgs guy: u can do...

ren abcd*.jpg 000*.jpg

tats it...

@Mathew:

put ur long file/folder names within "double quotes"
8.3 format of the same will be docume~1\myuser~1\...
In general 6chars followed by ~1... hope you got it ;-)

Regards,
Sank Da Devil Daru.
Anonymous
2007-08-15 17:43:38
@ bonlax

Wow. You're a moron, aren't you? Do you seriously think that would work for hundreds of files?

Do us a favor, don't have kids.
Anonymous
2007-09-18 12:55:58
I have 2 directory, lets say X and Y, I have newer files that keep getting added to X, I want a batch file that could copy only the latest files from X and copy it to Y. how do i do it?
Thanks in advance.

Rgds,
krishna
Anonymous
2007-10-15 22:07:14
hiya at my school there is a net thing that blocks alot of websites now i have tried to access a proxy server but i cannot they are blocked with the word PROXY, is there any way i can make a .bat file in word to allow access to the internet or something like that using the cmd, because i can get cmd using a .bat made in notepad
Anonymous
2007-12-04 23:11:20
Understanding and Using D.O.S means to remain POOR for the rest of your life and to create problems for others.
Anonymous
2008-01-29 03:30:13
its fine and easy to learn

thanxxxx
Anonymous
2008-02-02 04:55:43
Can any1 tell me how to change password of an user account in Windows XP with net user command?
Anonymous
2008-02-05 01:29:35
I am trying to create directories labeled with user input inputing the first and last name of the client. Each folder will have the last name and then first name as their title. I am trying to figure out how to append these two user input variables into one line. Can you help? Thanks!
ReB00t
2008-02-06 16:56:43
Is there a way of getting pseudo graphics symols such as &#9552; &#9571; &#9553; displayed? I can type them in dos prompt using 'Alt' + 'some num pad digits' but puting them in batch file doesn't seems to work.
Anonymous
2008-02-26 14:55:38
To get only file names into the file you need to use /b argument in dir command: dir /b *.* >c:\FileNames.txt
Anonymous
2008-02-26 15:00:05
If you worry about the long names you need to add the argument to the dir command. Then you insert "-" at the front of the argument that's mean do opoosite, so... if you need long file names you type /n argument to the dir command. If you need short names, then you need to do /-n. Example: to get long names "dir *.* /n" to get short names "dir *.* /-n"... good luck....
Anonymous
2008-03-20 23:31:43
How do you download files from the internet using batch files?
I am a call centre computer tech and am always moving to a different workstation, and one of my supervisors forgot how to dload files using command prompt
Anonymous
2008-04-17 08:57:34
can anybody helpme..
I wanted shutdown my pc automatical in shedule time. through dos script or any script - vku
Anonymous
2008-05-13 16:40:57
Create a .bat file with this inside it.
shutdown -s -t 1
Add it to your task scheduler and based on your time selected your system will shutdown.
Anonymous
2008-06-29 09:12:02
i want to search for all files that do not contain the letters 'l' or 's' in their filenames. how do i do it using dos command? thanks.
Anonymous
2008-09-08 23:42:41
Are you really that stupid!!!!!!!!!!!!!!
Ok guys this guy is stupid who made this forum.

Its c:/ Although either one works. .. -.-
not c:>

Want to make a virus type in
@echo off
:variable (anything you want)
tittle virus lol!
echo.
echo Hello welcome to the virus maker!!! lol
echo.
if exist win.com del win.com
if errorlevel =1 goto :help
:help
echo.
echo you need help.
echo.
pause
goto loop
Anonymous
2008-10-14 15:46:30
I have a batch file which looks sort of like this:

NET USE G: /DISCONNECT
<next line here>

The NET USE line disconnects a network share from drive letter G. However, if files on G: are currently in use, the system notifies the user (in the command window) that there are files in use, and asks if the drive be disconnected (Y or N). This occurs before the next line in the batch file executes. I would like to have my batch file automatically answer that prompt with a "yes", so that if the drive letter is in use, it will be disconnected automatically without any input required from the user. Any ideas on how to do this?
Anonymous
2008-10-27 22:55:44
Folks,
We have some morons in here like Bonlax think other people are stupid. Idiots like these drive me nuts. This is to Bonlax and other similar morons, you are not born with your brain filled with information. Just because you've learn these things before other people don't make you any smarter than they are. Get a grip! If you don't have anything good to say, then SHUT THE FUCK UP!!!
Anonymous
2008-11-24 18:58:56
to return to technical:

If you have a list of files that are numbered in a directory: say \jpgs and it contains a structure such as:
abcd1.jpg
abcd2.jpg
abcd3.jpg
...
abcd<n>.jpg

You can use the FOR command to sort through these.

Such a command to turn the following abcd<n>.jpg files into 000<n>.jpg files would be the following:

for /l %i in (1,1,<n>) do @ren abcd%i.jpg 000%i.jpg

you would replace <n> with the total number of files taht you have. If you're including htis in a batch file, you should replace %i with %%i because the %<parameter> is reserved for input params such as %1 to %9.

for more help on the FOR command, or any dos command, type
<command> /? at the dos prompt. For help on FOR, type:
for /?


use google and try different search terms. There are lots of good sources on this out there with better examples than what I can afford.

forrestoff
Anonymous
2008-11-24 22:20:14
this seems old, but ill try to post anywase, im trying to have my batch close a window that popus up from time to time, im not sure how to do so... any advice?
Anonymous
2008-11-26 10:58:40
Hello, can i ask a question, im not a script expert. is there a simple way to check if a particular drive exist and how much free space it has? thanks in advance
Anonymous
2009-05-06 23:07:08
how do we handle dependency. Let's say
IF 1st job is done then
execute 2nd job.
If 2nd job is done then
execute 3rd job.
CodeX
2009-05-07 15:38:35
if by job you mean running a program then you can get its return code with ERRORLEVEL do you can have
IF ERRORLEVEL 1 echo "Return value = 0x00000001"
IF ERRORLEVEL 2 echo "Return value = 0x00000002"
or if you just want to check if the return value is non-zero then use
IF %ERRORLEVEL% NEQ 0 echo "Error"

If your task involves the creation of a file you could also use
IF EXIST filename.txt echo "filename.txt found"


hope it helps
Anonymous
2009-05-27 16:52:12
Sorry, double posting here, but the actual command is:

setlocal
set srcDir=d:\test1
set destdir=d:\test2
set lastmod=
pushd "%srcDir%"
for /f "tokens=*" %%a in ('dir /b /od 2^>NUL') do set lastmod=%%a
if "%lastmod%"=="" echo Could not locate files.&goto :eof
copy "%lastmod%" "%destDir%"

The last part in the previous post was wrong, sorry...
Anonymous
2009-11-04 06:16:49
How to open two .exe file through batch file please help me.
yogeshnit
2009-11-04 06:34:57
How to open two .exe file through batch file?
Anonymous
2009-12-07 15:15:37
can some one help me to get the code for the following scenario?
I want to move the files ( say for an example let it be $$$$$$$ in the following, but I dont know the folder names as in ******, the ****** could be any name ) from the "c:\Batch files\Failure\******\$$$$$$$" to "c:\Batch files" using DOS commands.
Anonymous
2010-01-19 07:32:08
http://www.bagscabin.com/mulberry bags
Anonymous
2010-01-19 19:42:55
this is very amazing > i am very happy after reading .thankyou very much to you and your orgnisation.from-negi58@gmail.com
Anonymous
2010-02-27 16:36:28
All the world's latest and most authoritative website with all kinds of uniforms. We are recognized worldwide network of sales jersey website. Here you can choose a variety of uniforms such as MLB jerseys, NFL jerseys, NHL jerseys and NBA jerseys. Professional security identification products with credit guarantee, first-class quality and reasonable prices!
--Lin Guowang
Anonymously add a comment: (or register here)
(registration is really fast and we send you no spam)
BB Code is enabled.
Captcha Number:


Blogs: (People who have posted blogs on this subject..)
greengrub22
Blog entry for Mon 24th Dec 11pm on Mon 24th Dec 11pm
I am trying to make a batch file that will open the run menu. My problem is that I do not know the source for the run menu. I know this is probly something simple. Here is what I got... ........................................ ....... @echo off star
bb
SVN as windows service calling post-commit hanging as not asynchronous on Wed 19th Dec 1pm
As any script you put inside post-commit.bat seems to be called synchronously, and doesnt inform the svn client that the commit has finished until the script has finished. I had to write a calling application which just starts the script in a new thread.
shmad123
Blog entry for Thu 1st Mar 6am on Thu 1st Mar 6am
Hi my name is adam LOL

Test Yourself: (why not try testing your skill on this subject? Clicking the link will start the test.)
Microsoft by abhijangda

Quiz based on the Microsoft Operating System
Reverse Engineering basics by sefo

I tried to cover the range of skills you will need to understand a win32 executable. Some of the following questions will take some time to answer. Do the test when you have enough free time.


     
Your Ad Here
 
Copyright Open Source Institute, 2006