- Why Batch Files?
- Creating and Using Batch Files
- Batch File Programming
- Displaying Information in Batch Files
- Argument Substitution
- Argument Editing
- Conditional Processing with If
- Processing Multiple Arguments
- Working with Environment Variables
- Processing Multiple Items with the For Command
- Using Batch File Subroutines
- Prompting for Input
- Useful Batch File Techniques
Processing Multiple Arguments
When you have many files to process, you may get tired of typing the same batch file commands over and over, like this:
somebatch file1.dat somebatch file2.dat somebatch file3.dat ...
It's possible to write batch files to handle any number of arguments on the command line. The tool to use is the shift command, which deletes a given command-line argument and slides the remaining ones down. Here's what I mean: Suppose I started a batch file with the command line
batchname xxx yyy zzz
Inside the batch file, the following argument replacements would be in effect before and after a shift command:
Before Shift |
After Shift |
%0 = batchname |
%0 = xxx |
%1 = xxx |
%1 = yyy |
%2 = yyy |
%2 = zzz |
%3 = zzz |
%3 = (blank) |
%4 = (blank) |
%4 = (blank) |
This lets a batch file repeatedly process the item named by %1 and shift until %1 is blank. This is a common process, so I'll list it as a pattern.
The extended version of the shift command, shift /n, lets you start shifting at argument number n, leaving the lower-numbered arguments alone. The following illustrates what shift /2 does in a batch file run with the command "batchname xxx yyy zzz":
Before Shift |
After Shift |
%0 = batchname |
%0 = batchname |
%1 = xxx |
%1 = xxx |
%2 = yyy |
%2 = zzz |
%3 = zzz |
%3 = (blank) |
%4 = (blank) |
%4 = (blank) |
In actual use, you might want to use this feature if you need to have the batch file's name (%0) available throughout the batch file. In this case, you can use shift /1 to shift all the remaining arguments, but keep %0 intact. You may also want to write batch files that take a command line of the form
batchname outputfile inputfile inputfile ...
with an output filename followed by one or more input files. In this case, you could keep the output filename %1 intact but loop through the input files with shift /2, using commands like this:
@rem Example File sortmerge.bat @echo off rem be sure they gave at least two arguments if "%2" == "" ( echo Usage: %0 outfile infile ... exit /b ) rem collect all input files into SORT.TMP if exist sort.tmp del sort.tmp :again if not "%2" == "" ( echo ...Collecting data from %2 type %2 >>sort.tmp shift /2 goto again ) rem sort SORT.TMP into first file named on command line echo ...Sorting to create %1 sort sort.tmp /O %1 del sort.tmp