Making folders and debugging scripts

In we will:

 Note  Each Lesson relies on your files from the previous one. It's better to use your own files, but if you can't, download a copy of files as they were at the end of Lesson 7 and click instructions. Remember you can if you prefer.

Sample file content in BKSETUP.BAT

The first part of the plan for BKSETUP.BAT was:

  1. Initial setups:
In Lesson 7, we learnt how to create files with . We'll use this technique in BKSETUP.BAT to create files. The plan is to create one small file in . Then we copy it several times, with various names, to create a known set of sample files. Then we'll have a reliable set of sample source files to help with developing our backup script.

Open BKSETUP.BAT

Open the BKSETUP.BAT script in Notepad with , as usual :

Strange names are often used for temporary files

We must give our sample file a name. When we create a new file, we must take care not to overwrite an existing file with the same name that might contain valuable data. Batch script writers sometimes use peculiar names with characters such as  {  and  }  (which are valid, if unusual, in filenames) to avoid conflicts.

We'll create our workfiles in the folder

However, since we'll create our workfiles in the special folder, where no valuable data are stored, we shan't need {weird} names. To find the path to the folder, we expand the corresponding system environment variable: %TEMP%. And in Lesson 7 we saw how to access it reliably in scripts by adding the ,  .\ 

So the path to the folder is: %TEMP%.\

We'll start by creating a small file:SF – there's no need to give it an extension. Later, we'll give each copy of it a sample extension.

Use with to create a new file

In the initial section of our script, put a comment to explain we're creating a sample file. Then use an command with the operator to create a new file. We'll call the new file SF and create it in the folder :

Use with

Add a second line with and the append operator so we append to the file we created with the previous command line :

Run the script to check the file is created

You clicked File, Save? Let's run the script, afterwards we'll check the file was created. Just select the Quit option by replying  Q  :

Check with

Now use the command to check the file was created correctly :

Or check with

will also confirm a file exists, but it doesn't show what it contains :

 Note  Notice how Windows reliably accepts %temp%.\ as the path to a file in the folder in any command you use. If your folder is C:\WINDOWS\TEMP, you could use the literal path, but by expanding the variable and using the , your scripts will work more reliably on other Windows 95/98/ME computer systems.

Append two more lines

Let's complete the quatrain from the Rubáiyát. Use with the append operator , so that the new lines are appended to the first two :

Check the script again

You clicked File, Save so run the script again, just reply  Q  :

Check with

Now use the command to check the file was created correctly :

The earlier sample file was overwritten

The new (four-line) sample file overwrote the previous file, because our first line, with its operator, always creates a new file.

Now we have a sample file with style! And the syntax for writing files reliably to should be fixed properly in your mind.

 Note  Remember the distinction between (which erases any existing file and creates a new one) and (which appends to any existing file, creating a new one only if no same-name file exists already).

Leave clear when the script finishes

It's vital to clean up any file clutter a script creates. We need to add a command to clean up the sample file when the script finishes. It goes in the :CLEANUP section.

The command to delete a file is , so add the cleanup line now :

Run the script to check the file is deleted

You clicked File, Save? Run the script. This time no sample file remains after the script ends. Just select the Quit option by replying  Q  :

Try to the file

Confirm that the file has gone with a command :

Keep your folder clutter-free

The folder is for briefly created, transient workfiles. Our scripts will always delete any such workfiles before finishing. Many programs (particularly during installation) also use for temporary files, and they should always remove their workfile clutter.

 Note  Any files in your folder now are (almost certainly) temporary workfiles left over by programs that failed to clear up after they finished. We won't make this mistake. You can safely delete all such leftovers from . Windows avoids conflicts by refusing to delete ("access denied") any files that are in use at the moment.

But don't get distracted with tidying up your folder at the moment. When you've finished this Course, you can practise your skills by writing a Batch script to do it for you!

The Build option:
The Build option plan

 
We can now code the Build option of our BKSETUP.BAT script. The plan was:

  1. The script coding for each option:

The Build option will be used frequently

When we write the backup script, we shall constantly need to build and rebuild our test source folder, to confirm our backup script is working. The Build option of our script tool BKSETUP.BAT will do this for us. It will ensure we always have a known set of freshly created source files to backup.

Before we code the Build option, we'll practise all the techniques in immediate mode first.

Build a fresh test folder, erasing any existing one

We've seen how to make a folder with . Our test folder will be C:\BKTEST (choose another name if you have it in use for other purposes). Let's make it now :

Make a subfolder in the test folder

We'll need subfolders in C:\BKTEST and we make them in the same way. Let's make a subfolder in it called Text Files – since this subfolder name has  Space s in it, we need to enclose it in "quotes" :

 Note  Whenever a file or folder name has  Space s in it, we use "quotes" around it so that Windows interprets it as a single token (otherwise Windows will try to break it at each  Space , as if it were more than one specification). In this case, only the part with the  Space  need be quoted; so this would suffice:

c:\bktest\"Text Files" – or even – c:\bktest\Text" "Files

(where only the  Space  is quoted). However, it's better to "quote" the entire specification, because some commands  give a syntax error with mixed "quoted"+unquoted forms.

For example, the attrib command (we meet it in a later Lesson) won't accept mixed "quoted"+unquoted specifications.

Add a file to C:\BKTEST

We'll need to add sample files to our test folder. We'll practise by copying our HW.BAT file (any existing file would do). The command to copy files is , try it :

Remember how to get help when you need it

To remind yourself later about using commands such as , remember you can:

The Course Reference shows syntax examples and details that aren't in the /? brief help, but it doesn't repeat information in brief help, so use both when you need a reminder.

Now it with a new name

We can copy HW.BAT and give it a new name in the process, making a second sample file in the test folder :

 Note  By changing the extension of HW.BAT, we make it invalid as a Batch script. However, we're simply using it as a sample file that we might want to backup, so this doesn't matter.

Using s with

We'll try one more practice operation. We'll use the *.txt to all our .TXT files to the C:\BKTEST\text files subfolder and rename all the copies to .DAT files in the process.

Remember to "quote" the destination folder, it has  Space s in its name :

 Note  A copies the files in the order they happen to be in the folder index. Some defragment utilities sort folder index entries. So, the precise order your files are copied may differ from ours. The four files should all be there in the report, however.

Use to list our test folder

Use to list all the items we've added to our test folder. Remember to use the /s (include subfolder contents) switch :

Removing an existing folder and contents

Our BKSETUP.BAT script will often need to build a fresh test folder with sample files, just as we have. When it does so, it needs to remove any existing folder (and contents).

We saw in Lesson 7 that can be used to remove a folder. However, first we deleted the file it contained. won't remove a folder that isn't empty. Try it :

 Note  Remember that "directory" is just another term for a simple folder.

We need

The command we need is . This extremely powerful command will erase a folder and its contents (including any subfolders in it, and their contents, too). Always use with great care. It can erase huge numbers of files in one operation.

Use now to remove our C:\BKTEST test folder :

 Note 1  Replying to prompts sometimes requires you press a  Key + Return , and as we'll see in later Lessons, sometimes merely a  Key  press alone.

 Note 2  In a script, you can avoid the need to confirm by adding the /y (automatic Yes) switch. This is not a good idea in immediate mode, where the warning prompt is useful. Also, in a script we can silence the Deleting... report with >NUL

No error message if folder doesn't exist

The command doesn't report an error if we use it to delete a folder that isn't there. Try it again with C:\BKTEST, which we've already removed :

The Build option:
Now we can write the code for this option

 
It's time to put all we've learnt into our BKSETUP.BAT script Build option. The coding will be very similar to our immediate mode practice. The main difference is that where in immediate mode we used the text:

C:\BKTEST

in our script, which has the source folder set in SRC, we will normally use:

%SRC%

With SRC we won't use the

Now we know about the for the foldername in , one further question arises. Since our folder is in a variable, should we always use the safe combination  .\  when we add a further file or foldername to it, instead of just  \ ?

The answer is no. We won't need the special suffix, since we're setting the variable in our script. And we won't add a spurious backslash to the source foldername we store.

We need to make the source folder

The Build option needs to make the source folder, C:\BKTEST, and we need some sample subfolders, too. So in it, we'll make a DATA subfolder and a Text Files subfolder. The code goes in the :BUILD section :

The SRC variable is expanded

It's very important to understand how to use a variable in this way. At the start of our script we set SRC to C:\BKTEST, so when our script is executed, Windows expands:

This: to this:
%SRC% C:\BKTEST
And so these: are expanded to these:
MD %SRC% MD C:\BKTEST
MD %SRC%\DATA MD C:\BKTEST\DATA
MD "%SRC%\Text Files"   MD "C:\BKTEST\Text Files"

Test the script

You've clicked File, Save to save those lines, so let's test the script :

 Note  If you see any error messages, check the lines just added. Remember the simple debug technique: add ECHO ON (on a line on its own) before any suspect lines and add @ECHO OFF (also on a line on its own) after them. This turns on for just those lines, and will normally show you what is wrong.

Did it work?

Were the new folders added? The easiest way to tell is to rerun the script :

The folders were already there the second time

The three error messages tell us two useful things:

  1. The folders were built the first time, since on the second run, we received three error messages to say they already exist (the error message for a long folder name – our Text Files – is slightly different from the error message we receive when we try to make the first two named folders)
  2. We need to use first, to make sure any existing folders are deleted before we build the fresh ones (remember, if there are no existing folders, doesn't give an error message, so we can simply use first, regardless of whether there is an existing source folder or not.

Add the line

Add a command to remove C:\BKTEST first (this will remove all its subfolders and their files, too). Use the /y switch to suppress the confirmation prompt, and add >NUL to suppress the deletion report :

We hard-code the folder

Notice that we don't expand our variable SRC with . It would work perfectly well, but suppose we (accidentally) set our SRC variable wrongly while editing the script? Perhaps to an existing data folder, and then ran our script with option  B ? The script would wreak havoc, deleting that folder with all its contents (including subfolders).

It may not seem a very likely accident, but always play safe with .

Test the script again

You've clicked File, Save, so test the script again :

Check the folders are correctly in place

All is now well. Let's confirm that the test folder and its two subfolders are being created correctly. Use to list C:\BKTEST contents. Use the /s switch although there are no actual subfolder contents to be listed. Adding this switch makes include the full path specification for the two subfolders :

Nothing can possibly go wrong?

The BKSETUP.BAT script is just a tool for us to use (while we develop our backup script). And we wouldn't unintentionally select the  B  option, and as a result, instantly erase and rebuild our test folder by mistake. No, it couldn't happen... but we'll add a confirmation sub-menu anyway, just for practice.

Adding a confirmation sub-menu to :BUILD

We have the task description stored in TASK, so we can use that to display a confirmation question:
if we this:  Really %TASK%?
it's expanded to this:  Really Build fresh test folder?

Add this line (with a comment). It goes before the operation :

Display the options

We need a message to explain the two options. It's usually better to display the most likely option first –  Y  for Yes, in this case.

If we select  N  (for No), it's probably because we hit the wrong option in the main menu, so an  N  choice needs to take the logic flow back to the main menu again.

We'll also add a blank display line below the menu choices, as usual :

Test the script

The sub-menu messages should line up with the main menu display. We haven't added the command, so the sub-menu won't work yet. But let's test the script to check the alignment of the displayed messages :

Adjust the alignment

All the menu reply letters displayed in the sub-menu should be vertically aligned with the main menu, as above. Correct alignment makes a menu easier to use.

Add the second command for sub-menu

We know that yn is the default reply list for . We could use this default list, but it gives return code 1 =  Y  and code 2 =  N .

We prefer to list our descending tests in the same order as the menu display (so the script is easier to read). So we need return code 2 =  Y  and return code 1 =  N . Therefore, our reply list must be in the order: /c:ny

Add the new line. The sub-menu text is the same width as the main menu, so use "quotes" for the Please choose , and put 15 extra  Space s first, as before. Then add another blank display line, using ECHO. :

Descending order for testing

Before we test the alignment of the choice text prompt, we'll add the tests to handle the replies. We must test for 2 (reply  Y ) first. You do remember the test is for whether the actual return code is greater than or equal to the number we test for, don't you?

The reply  Y  (return code 2) will need to go straight to the line. So we'll need a new label to jump to: it will have to go on the line before the command.

We'll use a commented label :BUILDYES confirmed. Remember that in the command we conventionally omit the colon from the target label (although you can include it, if you prefer).

Code the final option unconditionally

The reply  N  (return code 1) will need to go to the main menu, as we said, and we already have a :MAINMENU label to jump back to. The  N  option is rather like a quit option (it abandons the Build option that was selected).

So, as usual, we'll code it with an unconditional jump as we did for Quit in the main menu. We know must be working properly (or we wouldn't have reached this point in the script), so nothing can possibly go wrong. But we'll keep to the safe-menu principle anyway.

Add the test, the unconditional jump, and the new label :

You remembered to click File, Save?

Review the test logic

Before we test the script, let's remind ourselves why we must test for 2 (reply  Y ) first.

Suppose we tested for 1 (reply  N  given) first. Remember that a test for 1 really means: is the actual code returned greater than or equal to 1? If we test for 1 first, and if the actual code were:

As a result, we'd never get to the test for 2 at all. So we must test for 2 first.

To check the script, first remove C:\BKTEST

When we select the  B  option in the main menu, we'll now see a sub-menu asking for confirmation. To check the new logic thoroughly let's first use manually to remove the C:\BKTEST folder :

Check it's gone

Check the C:\BKTEST folder really has gone :

First, we won't confirm the build option

We've saved all the changes, so now run the script. This will be the sequence:

The  Exercise  window will remind you of the sequence :

Check the folder isn't there yet

We deleted the test folder before the test. We answered  N  to abandon the Build option, so let's check that the C:\BKTEST folder was not recreated :

Next, we will confirm build at the sub-menu

This time we'll confirm the option and build the folder. Run the script, press  B , then press  Y  at the sub-menu :

Check folders are there

Check the script has recreated the test folders by using :

Debug any errors you see

If you see any error messages, check the lines we've just added. Remember the simple debug technique: add ECHO ON (on a line on its own) before any suspect lines and add @ECHO OFF (also on a line on its own) after them.

You can also use this  Exercise  window to check all the new lines we've added to the Build option of the script :

That completes main logic flows

The main logical flow of our script tool is complete. All that remains is to add some code that will use our sample file to create the test files, and make file changes. We'll work on that in the next Lesson.

What we have learnt

In this Lesson we have learnt how to:

Course Reference

Remember that the Course Reference grows, Lesson by Lesson. The command has several important uses with s. Now we've covered , you'll find examples of using with s by clicking on and reading the Course Reference.

The Index has the Syllabus for the next Lesson, where we'll finish the code for the Build option. See you then.

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