- 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
Using Batch File Subroutines
The CMD shell lets you write batch file subroutines using the call command. Although the new ability to group statements with parentheses makes batch file subroutines somewhat less necessary than they were in the past, the subroutine is still an important tool in batch file programming.
For example, in a task that involves processing a whole list of files, you might write a batch file subroutine to perform all the steps necessary to process one file. Then, you can call this subroutine once for each file you need to process.
In the old days of COMMAND.COM, batch file subroutines had to be placed in separate BAT files. You can still do this, but with CMD, you can also place subroutines in the same file as the main batch file program. The structure looks like this:
@rem Example File batch1203.bat @echo off rem MAIN BATCH FILE PROGRAM ------------------------ rem call subroutine "onefile" for each file to be processed: cd \input for %%f in (*.dat) do call :onefile %%f ← subroutine called here rem main program must end with exit /b or goto :EOF exit /b rem SUBROUTINE "ONEFILE" --------------------------- :onefile echo Processing file %1... echo ... commands go here ... exit /b
The call command followed by a colon and a label name tells CMD to continue processing at the label. Any items placed on the call command after the label are arguments passed to the subroutine, which can access them with %1, %2, and so on. The original command-line arguments to the batch file are hidden while the call is in effect.
Processing returns to the command after the call when the subroutine encounters any of these conditions:
- The end of the file is reached.
- The subroutine deliberately jumps to the end of the file with the command goto :EOF.
- The subroutine executes the command exit /b.
Normally, any of these conditions would indicate the end of the batch file, and CMD would return to the command prompt. After call, however, these conditions just end the subroutine, and the batch file continues.