Thursday, July 8, 2010

Batch File Tutorial

In this post we will try to explore basics of Batch file programming.
Batch files are simple windows executable with .bat extension; everything written in batch file is executed on command prompt line-by-line.Its normally used to automate processes.
Lets create our first batch file
Go to notepad
type:

1]
@echo on
echo This is my first batch file

save file as hello.bat
Output will look like this
a black screen will flash.. and nothing
so now do this right click on batch file and say 'edit'
after last line type
' pause' dont forget to save
then run Hello.bat
You will see following output


As you press any key it disappears... 


So what we learned here is batch files by default dont show output on screen
you can use pause commnad to see it.
The 'pause' command will pause the execution after you press any key it resums.

2]
What echo means?
Now open hello.bat edit very first line to
@echo on

save and run you will output like above..
but if you set echo off
@echo off
directories wont show up..see image.


so echo off hides root directories and its better to set echo off

3]
Now we will see use of 'cls' and 'msg *'
cls clears srceen and any previous output.
msg * generates a pop up message.
create try3.bat with following code

@e cho off
echo He llo This is a te st
pause
cls
echo I am te sting pause
msg * The End
pause

output
First 'Hello this is test
Press any key to continue...'
this message appears after you press any key screen gets cleared and a pop up saying The End is displayed.

So you learned how cls clear screen and msg * generate a pop up...
experiment with commands on your own.
4]

Now i tell you commnad which are usefull and do something for real.
'start' command

make try4.bat n type

@echo off
echo Now notepad will open..
pause
cls
start notepad.exe

see output when you press any key notpad will run.

5] Now lets learn some control
next point will teach you how to do switch case like control in batch file
for this we use
'if' and '%' commands

create following try5.bat file

@echo off
echo This is a try5 batch file
echo If you want to open notepad type 1 and press enter
echo If you want to open paint type 2 and press enter
set /p option=
if '%option%'=='1' start notepad
if '%option%'=='2' start mspaint
pause

See output yourself...
its woriking guys...

No comments:

Related Posts with Thumbnails