How-to: Use Loops and subroutines in a batch file.

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 commands

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

(追記) (追記ここまで)
Copyright © 1999-2026 SS64.com
Some rights reserved

AltStyle によって変換されたページ (->オリジナル) /