Hello World

You should complete the Introduction (which is really Lesson Zero) first. It shows you how to create and configure the customized  BatchWindow  and how to use our specially-designed multi-window layout.

Remember, you can hover the mouse over or items to read further details, and if you prefer (click for details). And bear in mind that this Course is for Windows 95/98/ME (click here users).

In , we'll cover some groundwork. This will also help you become fluent in using the multiple Course windows on screen. We shall:

You can click on any item in dark blue (such as ) to read about it in the Course Reference window. Use it only to review and expand on what you've learnt in a Lesson. Don't try to learn about new commands from their Reference window details.

This is an InfoBox. We use it to include incidental extra details, or reminders. An InfoBox works like a dynamic footnote you call up with your mouse. The details don't intrude into the main text, but are easily consulted. Your cue to find them is either a or a term in purple text. All these InfoBox notes are built into the page, so they work on- or off-line. Marilyn Monroe, born June 1926, Los Angeles, Norma Jean Mortenson, but baptised Baker. Childhood in several foster homes; a full-time photographic model - 1946; at Lee Strasberg's New York Actors' Studio - 1956. Her 30 films include: Bus Stop 1956; The Prince and the Showgirl 1957 (with Laurence Olivier). Died August 1962, California. Icon of exploitation of youth and beauty. We use purple text as well as as an InfoBox cue. These InfoBox data are coded only once in the page. But we often tag several occurrences of a new term with its InfoBox. This is so you can summon up the details any time you see the term. It's easy to ignore the repeated details if you don't need them - just don't MouseOver the purple term. In Windows 95/98/ME, this is the command processor. It runs MS-DOS commands, and it contains the code to process your Batch commands.
 NT/2000/XP  The command processor is CMD.EXE. This also contains the Batch processing code, and this has been enhanced. That is why some details of Batch syntax are different from Windows 95/98/ME.
CMD.EXE is the standard command processor for Windows NT/2000/XP. It's in the Windows\SYSTEM32 folder. In CMD.EXE, the usual Batch commands have the same names as in Windows 95/98/ME, but they have more features. Their syntax can be different, as a result. We'll indicate some of the differences to expect (watch for  NT/2000/XP  flash). In Win95/98/ME, .BAT is the standard Batch file extension, and Batch files are interpreted by COMMAND.COM.
 NT/2000/XP  You can use either .BAT or .CMD, since CMD.EXE will handle both extensions. If you are writing Batch files to run on both 95/98/ME and NT/2000/XP systems, they will need to have a .BAT extension (and need to be written to cope with syntax differences).
We use Batch file and Batch script as equivalent terms. In this Course, we'll often use the terms interchangeably. Using "script" emphasizes similarities to other scripted (interpreted) languages, such as Windows Script Host. The extension .CMD can be used for NT/2000/XP Batch files, if you wish. CMD.EXE will accept either a .BAT or .CMD extension.  Note  A file that has the extension .CMD will not be recognised as a Batch file in Windows 95/98/ME – so using .CMD is a handy way to avoid any Batch files with enhanced NT/2000/XP commands being used accidentally in Windows 95/98/ME. A Windows 95/98/ME DVM (short for Dos Virtual Machine, also called an MS-DOS window) is a Shortcut to the command processor (COMMAND.COM). It also uses the files WINOA386.MOD and VGAFULL.3GR, together with a hardware mode of your CPU, called V86 (=Virtual 86 mode, the "86" relates to a simpler precursor of the Pentium). A DVM is a PC simulated inside your PC!
 NT/2000/XP  A CMD.EXE window is a 32-bit process. It doesn't use V86 mode.
Expanding COMSPEC allows you to refer to the command processor in your Batch files without needing to know exactly which folder it's in, or exactly what it's called. MS-DOS (=the MicroSoft Disk Operating System) included Batch processing from version 1.0 (August 1981). It was added to help IBM engineers run long lists of commands to test MS-DOS on the IBM Personal Computer original prototype. The Batch language developed steadily through later versions of MS-DOS, and is always installed in Windows 95, 98, and ME (but many users don't know this).
 NT/2000/XP  An enhanced version of the MS-DOS Batch Language comes with Windows NT/2000/XP.

Commands can be immediate, or scripted

Most commands we'll use also work if you type them at the prompt in the  BatchWindow : this is called immediate mode. A command used in immediate mode is carried out as soon as you press  Return  at the end of the line.

Batch scripts will always run in Windows

A Batch , also known as a Batch , is a list of commands. It's executed by a command processor (a special program). Windows 95/98/ME uses the command processor (which is always installed so Batch files will always run).

 NT/2000/XP  Although includes a version of , for Batch work it's better to use , since it has more powerful Batch features.

Batch scripts are plain text files

Batch scripts must be plain text files, created with a text editor. With a Word Processor, such as WordPad, which saves files in a special format, you must choose the option:

 Save as type : Text documents  otherwise your scripts will fail to work.

We shall always use Notepad for our Batch work in this Course. However, unlike most Notepad files (normally .TXT type), our files will have the extension – this is how Windows recognises them as the Batch file type.

 NT/2000/XP  In you can use either or as the file extension. will interpret either file type. We use only in the Exercises, since this will work for both Windows 95/98/ME and .

Remember how these interactive pages work

By the way, remember that you can:

Displaying text:
displays text messages on the screen

 
A good script displays clear instructions and progress reports on the screen. The command to display text is , and almost all the scripts you write will use it.

A "Hello World" Batch script to begin

Batch scripts are computer programs. And the traditional way to begin writing computer programs is with a program that says: "Hello World". is just what we need. First, we'll practise in immediate mode, in the  BatchWindow , then write a simple script.

The  Exercise  window avoids the need for notes

When you click the button on this page, the small  Exercise  window will appear in the top right of the screen. The  Exercise  window has all the instructions you need for each Exercise (and often has extra information, too).

The  Exercise  window also repeats the simulated screen images, which show you what you can expect to see. This is so you can easily compare your results with ours, before you need to return to this main Lesson window (and lose sight of your results).

Keep  Exercise  on top right, others bottom left

The  Exercise  window is deliberately quite small, to allow you to read it while you work in other windows open in the main bottom left area of the screen. For this reason, you'll often need to use the  Exercise  window scroll bar (that will appear on the right of it) to read all the details. Click the button now, and follow the instructions :

Making the immediate command into a script

That line does what we want for our Hello World task, so let's make it into a script. It isn't a script yet, because we haven't typed it into a file. Our file will need the right Batch file extension, too, so let's call it HW for Hello World.

You could call it HelloWorld if you wished. However, we'll be running the Batch files we write in this Course by typing their names at the prompt, so we'll keep names short.

A Batch script is just a simple text file, so the Windows Notepad text editor is all you need (feel free to use your favourite text editor if you prefer, but we'll demonstrate with Notepad because it's always part of Windows). You can start the Notepad editor with an immediate mode command from the  BatchWindow  like this (click now):

Notepad starts up minimized as a button

What happened was that Notepad created an empty file called HW, in the folder C:\CSW. Using the command, as here, is neater than opening Notepad from the normal Programs menu because this command line sets both the filename and folder for our script file. The Notepad window was minimized (=just a button on the Taskbar). That's because we used the /min (=minimized) switch of the command. We did that so the Notepad window wouldn't get in our way for the moment.

If you found that confusing, or got into a tangle with the windows, try it again. To do so properly, you'll need to delete the HW file or you won't see the Notepad dialogue box asking if you want the file created. If you do want to try again:

Type the script in Notepad

Our script consists of just one line: ECHO Hello World. It's important when typing scripts to make sure the last line ends with a  Return , otherwise Windows 95/95/ME puts a spurious blank line on the screen when the script is run. Type the single line in Notepad, making sure you press  Return  at the end, like this :

Remember to save the changes

 Note  You must remember to click File, Save in Notepad to save any change we make. If you prefer, you can use  Alt + F ,  S  (=hold down  Alt  while you press  F  key, release both, then press  S  key). This is the keyboard alternative to the mouse method.

Keep Notepad open to maintain window position

Unlike our  BatchWindow  Shortcut, Notepad doesn't store its last-used window position, so keep it open during the Lesson, then you won't have to re-position it to read from the  Exercise  window.

Don't use Notepad maximized (where its window would fill the display) or you won't be able to read the notes in the  Exercise  window.

Run HW.BAT in the  BatchWindow 

We've saved the script as HW. To run any script, we can just type its name at the prompt in the  BatchWindow . Try it now. This is what you'll see :

 Note  We didn't add the extension, it's optional here. You would need to add the extension if there were files HW.COM or HW.EXE in our CSW folder, since .COM and .EXE files take precedence with COMMAND.COM. In that case, we could specify name and extension: hw.bat so as to ensure it was our Batch script that ran.

 NT/2000/XP  You won't see as many spurious lines displayed.

Turn off to stop script lines echoing

Our "Hello World" is in there, but amidst a lot of other clutter, too. When Windows runs our script, it displays each command in turn, then executes it. This is very useful when we're debugging scripts, but it makes a mess on screen. We need to turn off echoing.

Brief help with /?

Remember that you can get brief help with most Batch commands by using the help switch (/?). Try using it with in the  BatchWindow  now :

Turning OFF and ON again

As well as echoing text to screen, will turn off (and on) the display of commands in a Batch file. Windows always starts with command turned on. ECHO OFF will turn it off. In immediate mode, ECHO OFF suppresses the prompt that you normally see on screen.

Try that now. In the  BatchWindow , type echo off, then press  Return  a few times. The prompt is no longer displayed. Then type echo on to restore normality :

ECHO OFF stops subsequent command lines displaying

We need ECHO OFF in our script to prevent the script command lines themselves being displayed as the script runs. It needs to be the first line of the script (because it affects only the lines that follow it). Add it to our HW script :

 Note  The de-emphasized text  such as this  in the simulation marks the text already there, so that you can see clearly exactly where your  new text  goes.

Run HW.BAT again

With the change saved, run HW in the  BatchWindow  once more :

 NT/2000/XP  You may see an extra blank line displayed before the prompt returns in above, and (and following Exercises) below.

Use the prefix to turn off echo of a single line

This is better, but the ECHO OFF command itself still shows on screen. Its effect only applies to the lines that follow it. You can turn off display of a single line by typing the line with an prefix. So let's fix the problem in our script like this :

Run HW.BAT once again

With the change saved, run HW in the  BatchWindow  once again :

Most scripts will start with an @ECHO OFF

Now the script writes "Hello World" to the screen, with no other clutter. We could have just used the command to prefix our original (single) line, making it:

@ECHO Hello World

However, while using to prefix each line is fine for a tiny script, we shall soon be writing longer ones.

Most of our scripts will start with @ECHO OFF to prevent the display of each line of the script as it runs. Of course, while you are debugging a script, it can be useful not to use @ECHO OFF. Then, if there is a problem with the script, you will see what line is being executed when the problem occurs.

In debugging longer scripts, you can start with @ECHO OFF, then use the command ECHO ON later, at any point, to turn on display of subsequent lines of the script as it runs. We don't need the prefix for the ECHO ON, since it affects only subsequent lines, and we would use it only when echoing was already off.

Used on its own, the command simply reports whether echoing (displaying) of script lines is currently on or off. Try it now, it will report that is on :

clears the screen

By the way, when you are working in immediate mode, and you want to clear previous work cluttering the screen, use the command (clear screen). You'll find that clearing the screen from time to time makes it easier to work in a window. It's probably about time you did so :

 Note  The simulation shows you the effect, both before and after the command.

's dual role can upset text displays

As we've seen, is used both for changing and reporting the echo state, and for displaying text. In Windows 95/98/ME, these roles may conflict. Let's use Notepad to make a new script called HIGHNOON and see what can happen :

Did you remember to press  Return  at the end of the final line? And to make sure the new file was saved in the C:\CSW folder?

 NT/2000/XP  The command doesn't suffer from the conflict Windows 95/98/ME users will see in but you should work through anyway, so you will be aware of the problem should you need to use Windows 95/98/ME systems.

Notepad: remember to take care with file types

 Care  When using Notepad, be careful about file types when you save files. Notepad would normally add a spurious extra .TXT extension if we saved our script as type Text Documents (the script would then fail to work until we renamed it properly).

You might have noticed that this didn't happen when we saved HIGHNOON in , even though we left the  Save as type : Text documents. This was because we had previously opened Notepad with a file when we started.

Notepad remembers an extension already used in the current session (while you keep its window open) and doesn't append a spurious .TXT to it (however, just to be sure, make certain there isn't a spurious extra .TXT extension added to HIGHNOON)

If you're unsure when saving a file with Notepad, you can avoid a spurious .TXT extension being added if you:

Files with extension are registered in HKEY_CLASSES_ROOT by default.

 NT/2000/XP  The alternative extension is also registered by default.

HIGHNOON.BAT doesn't work properly

With changes saved, try running HIGHNOON to see what happens :

 NT/2000/XP  You won't see this conflict in , both lines will display correctly. However, it's worth being aware of the problem, in case you need to write Batch files meant to run under Windows 95/98/ME and

The initial word "On" produced a conflict

Remember that our script is:

@ECHO OFF
ECHO Do not forsake me, Oh my darling 
ECHO On this our wedding day

The last line produces an error because it starts with the word On, which is one of the commands (a line of text starting with Off would also produce an error). In fact the faulty line doesn't even turn echo on, it just writes a spurious ON. This is because any other text following an ON or OFF instruction for produces confusion.

Using the ECHO. syntax is a reliable technique

The standard way to separate from the following text to be displayed is with a  Space . The first  Space  following is always ignored (so if you need your displayed text indented by say, five  Space s, you must put six  Space s in your script)

There are eleven other special characters you can use immediately after that, just like the first  Space , are not themselves echoed.

They are:  Comma   ;   =   :  and  Period   /   \   +   [   ]   " .

The first four work like a  Space : they don't stop the action of a following ON or OFF. However, any of the last seven stop these words being treated specially (this is exactly what HIGHNOON needs). The usual one to use is the  Period , thus ECHO.

Instead of trying to remember to use a  Period  whenever our text begins with an on or off, we'll always use ECHO. whenever we display text. The only time we won't use it is when we really do want to turn echo on or off.

 NT/2000/XP  When these  Comma   ;   =   :   Period   /   \   +   [   ]  are used immediately after , they aren't themselves displayed (but there isn't any ON/OFF conflict to group them by). However, you can't use  "  immediately after in this way. In the  /  works best (fastest) immediately after .

Correcting our script

Now let's alter our HIGHNOON script by using ECHO. each time we merely display text. Change it to this :

The wedding's back ON

With changes saved, run the corrected version of HIGHNOON. This time you will see the text displayed as we intend :

Use ECHO. on its own to create a blank line

Remember, the initial  Period  is not displayed, it just ensures that the rest of the line is treated as ordinary text. You can use ECHO. on a line alone to create a blank line on screen. This is often useful in scripts to break up text and make screen output clearer. Let's try that in our HIGHNOON script. We'll make a blank line display both above and below the two text lines; make the changes in Notepad :

The final showdown

Did you remember to press  Return  after you added the second ECHO.? If you didn't, do so now. It is the (new) last line of the script, and a script should always end with a properly terminated line, one that ends with a  Return . You don't need to add any further blank lines afterwards, it's sufficient that the last line of every script is properly terminated (this prevents a spurious blank line in the display when the script runs).

With changes saved, run the script a last time :

That's enough ing for now. When you've completed , use the command in the  BatchWindow  to clear the screen.

Variables:
Stored in environment

 
In the second half of this Lesson, we'll learn to use Environment Variables. These are a way of storing small pieces of text in a special area of memory called the environment. They are much simpler than the variables in most programming languages; there are only three principal things you can do with them:

Nevertheless, they are the basis of many powerful script techniques. Any variable you set in a normally retains its value until it's cleared, or reset, or you end your current session (close the window).

Setting a variable

A variable name can contain most normal characters, including letters and digits; but you should avoid variable names starting with a digit, they conflict with replaceable parameters (which we shall learn about in later Lessons). To set a variable named SRC to, say C:\BKTEST (a foldername we shall later use for testing), you use in the window like this :

Expanding a variable

The name of the variable, src, is changed to uppercase as it's stored, so it doesn't matter whether you use upper or lowercase in the command. However the case of letters in the contents (the part on the right of the  =  sign) is preserved.

In our scripts, we'll always use uppercase for variable names to help them stand out: eg SRC (this is just a convention). We don't bother when simply working at the prompt.

To make use of the current contents of a variable, that is, to expand the variable contents, you surround the name with  %  characters. To expand the variable we have just set, src, you would type %src%. When you type %src% at the prompt (or in a script), it's as if you had used the exact text stored in the variable. Try it :

This is useful where, say, a foldername is going to be used many times throughout a script. We can set it in a variable once at the start, then use the variable throughout the script. If we want to change the folder later, we need only change the initial assignment.

Storing messages

Variables are often used to store messages, for example :

Expand the message

Now try using the message, by expanding the variable, like this :

Global variables

Environment variables can be set in the Windows startup files; then they're available whenever you open a window. These are called global variables (there is also a utility, WINSET.EXE, provided on the standard Windows CD-ROM, to set global variables). Windows normally sets some important global variables for you:

winbootdir
The path to your windows folder, set in real-mode and in the Windows GUI. Usually set to C:\WINDOWS; this setting is taken from the file MSDOS.SYS.
The path to , the command processor that runs our scripts. It's usually set to C:\WINDOWS\COMMAND.COM in Win95/98/ME
 NT/2000/XP  usually set to C:\WINDOWS\SYSTEM32\
If you ask to run a program (or a script), Windows searches certain folders for it by default. The list of foldernames Windows searches is set in the variable, with a ; between each, usually: C:\WINDOWS;C:\WINDOWS\COMMAND
 NT/2000/XP  will include C:\WINDOWS;C:\WINDOWS\SYSTEM32
TEMP
The path to the temporary folder. It's usually set to C:\WINDOWS\TEMP
PROMPT
This specifies how the prompt looks. Usually set to $p$g. The $p means display and path to , and $g means display a > symbol
windir
The path to your windows folder, set only in the Windows GUI. Usually set to C:\WINDOWS
You'll often see another variable. Unlike the global variables above, however, it's transient, and local to your :
CMDLINE
Holds the last command line used for an command. This may be a command you typed in immediate mode, or one used in a script. Any commands you use don't set CMDLINE, so it will probably still be set to: CMDLINE=start /min notepad HW.BAT ( is an command).
 NT/2000/XP  is an command, so it won't affect CMDLINE
 Note  CMDLINE is allocated a separate memory region by Windows, so it doesn't take up your precious environment space. Therefore, unlike other variables created transiently, there's no need to clear it.

System variables with lowercase names

As we said, names of variables you set with the command are always forced to uppercase. However, Windows sets the two variables winbootdir and windir with lowercase names. In Windows 95/98/ME, the command will not clear variables whose names contain any lowercase letters (so they are write-protected).

List current variables

You can list all the variables currently set (including the global ones) by using the command on its own. Try it now :

The first six shown are the usual system variables. You may have more listed (or some set to different values). The two we've just set are at the end of the list: SRC and TASK.

 NT/2000/XP  The normal list contains more variables.

If you have a printer attached to your system, and you want to print out a complicated screenful of text (such as the variables' listing above) from the  BatchWindow , click on the  BatchWindow   button on the Taskbar (so that it's the window with focus), and press the key combination  Shift + PrintScrn . This works for any window.

Clear the TASK variable

Now try clearing one of the variables we set. You simply set it to nothing. Make sure you don't put a space after the  =  sign. Clear the variable TASK like this :

Check that it's gone

Now list the variables that are set again, and check that TASK has been cleared from the current list :

A clear variable expands to nothing at all

If you use a variable that is clear, Windows treats it as if you typed nothing at all. Try using our TASK message again :

 NT/2000/XP  When you expand the undefined variable in , you see literal text instead of a blank space: %task% - finished

Clear SRC variable

Now clear the SRC variable in the same way :

Check SRC has gone

Now list the variables that are set again, and check that SRC has been cleared from the current list :

Your list will differ

Remember, there may be other variables set on your system than the standard ones we list here, and some of your standard variable contents may differ slightly from this list.

 NT/2000/XP  is an command, so it won't appear in CMDLINE

The standard variables are often used in scripts

The point of these standard variables is that your scripts can use, say the temporary folder, by referring to %TEMP%, without having to worry exactly what folder it is.

If you do this, your scripts will run properly on other people's machines that may have the temporary folder in a different location. This is important, because we shall use this folder for most of our transient working files.

Take care with spaces

Variable names (and their contents) can contain  Space s, but beware of accidents! For example: we'll set a variable called Norma Jean to the text value Marilyn Monroe. But, we'll make a mistake (trying to be neat) and leave a  Space  either side of the  =  sign when we assign the variable :

The  Space s are used

The text value now includes an initial  Space  thus:  Marilyn Monroe. That's not really a problem, we may even want it that way. However the variable name now includes a final space, thus Norma Jean , and it's easy to miss this detail.

If you didn't notice, or forgot, and tried to use the variable name without its accidental trailing  Space , it wouldn't work :

 NT/2000/XP  When you expand the undefined variable in , you see literal text instead of a blank space: Goodbye %norma jean%

Check with

There is no variable with that name, so we draw a blank. Check the variable list with a plain command :

Include the  Space  to use the variable

The list shows that the NORMA JEAN  variable name includes a  Space  at the end: you must include it in the name in order to use the variable, like this :

 Note 1  Any leading  Space s typed before the variable name don't matter, since always ignores them.

 Note 2  Any  Space s in the variable content (to the right of the  = ) are part of its content, including  Space s at the end of the line.

Clear the variable

Let's clear now. Don't forget the  Space  before the  =  sign :

Goodbye Norma Jean

Check that she's gone :

 NT/2000/XP  is an command, so it won't appear in CMDLINE

We'll take our cue from , and take our leave for this Lesson, too.

What we have learnt

In this Lesson we have learnt how to:

Remember, you can review items in dark blue (such as ) by clicking on them, or by using the Course Reference List Box at the top of each Lesson. In the Reference window itself, click on any dark blue items to follow up cross-references.

Take a well-earned break now. The Index has the Syllabus for the next Lesson, where we'll learn how to work in child shells, and take a look at return codes. See you then.

© Copyright 2003- Allen & Company. All rights reserved ©