Loops and subroutines

There are 2 ways to conditionally process commands in a batch file

IF xxx ELSE yyy - will conditionally perform a command (or a set of commands)

FOR aaa DO xxx - will conditionally perform a command several times (for a set of data, or a set of files)

Either of these can be combined with the CALL command to run a subroutine like this:

   @echo off
   IF EXIST C:\pagefile.sys CALL :s_page_on_c
   IF EXIST D:\pagefile.sys CALL :s_page_on_d
   GOTO :eof
  
   :s_page_on_c
   echo pagefile found on C: drive
   GOTO :eof
 
   :s_page_on_d
   echo pagefile found on D: drive

Without the : a second batch file will be called ...

   @ECHO off
   IF EXIST C:\pagefile.sys CALL Second_Batch.cmd

If the code does not need to return then use the GOTO statement like this:

   @ECHO off
   IF EXIST C:\pagefile.sys GOTO s_page_on_c 
   ECHO pagefile not found
   GOTO :eof
   
   :s_page_on_c
   ECHO pagefile found

To call a second batch file in a separate shell use CMD An important difference between CALL and CMD is the exit behaviour if an error occurs.

   @ECHO off
   IF EXIST C:\pagefile.sys CMD /C Second_Batch.cmd

"I knew of one little DO loop that ran for 48 hours, cost $14,000 and did nothing" ~ Richard Keeler

Related:
Syntax: Parameters - Command Line Parameters %1 %~f1
Syntax: Functions - How to package blocks of code


© Copyright SS64.com 1999-2013
Some rights reserved