Saturday, February 17, 2007

Writing .bat files / Part 1 / Hello World

You create a batch file by writing it in a text file then saving the file with the ".bat" extension at the end, this will tell windows that this is an executable batch file.

Here I will create a text file containing the following and save it as "test.bat":

echo "Hello World, this is my first batch file!"

The word 'echo' is a DOS command that simply tells the command shell to display the text message following it.

You can test your first batch file by opening a command line window. To open a command prompt window there are two ways:

First, you can go to Start > All Programs > Accessories > Command Prompt
Or, you can go to Start > Run then type in 'cmd' and click OK.

Once the command prompt is open, you can run your batch file by typing its name followed by enter:

c:\> test.bat

Make sure to change the directory to the location where the test.bat file was saved, in the above example it assumes it was saved in the C:\ top folder. If it was saved in a different location, e.g. F:\my_folder then you can change directories by typing:

c:\> cd /D F:\my_folder
f:\my_folder> test.bat

The output:
f:\my_folder> echo "Hello World, this is my first batch file!"
"Hello World, this is my first batch file!"

Notice that the string got displayed, but also the command 'echo' got displayed too. To hide the commands being executed you can add "@echo off" at the top of the test.bat file.

@echo off
echo "Hello World, this is my first batch file!"

Now executing test.bat would result in:

F:\my_folder>test.bat
"Hello World, this is my first batch file!"

Congratulations, your first batch file is ready. Unfortunately, till now it does nothing interesting other than print a message.

No comments: