[batch-file] How to run multiple .BAT files within a .BAT file

I'm trying to get my commit-build.bat to execute other .BAT files as part of our build process.

Content of commit-build.bat:

"msbuild.bat"
"unit-tests.bat"
"deploy.bat"

This seems simple enough, but commit-build.bat only executes the first item in the list (msbuild.bat).

I have run each of the files separately with no problems.

This question is related to batch-file cmd

The answer is


Try:

call msbuild.bat
call unit-tests.bat
call deploy.bat

Looking at your filenames, have you considered using a build tool like NAnt or Ant (the Java version). You'll get a lot more control than with bat files.


To call a .bat file within a .bat file, use

call foo.bat

(Yes, this is silly, it would make more sense if you could call it with foo.bat, like you could from the command prompt, but the correct way is to use call.)


You are calling multiple batches in an effort to compile a program. I take for granted that if an error occurs:
1) The program within the batch will exit with an errorlevel;
2) You want to know about it.

for %%b in ("msbuild.bat" "unit-tests.bat" "deploy.bat") do call %%b|| exit /b 1

'||' tests for an errorlevel higher than 0. This way all batches are called in order but will stop at any error, leaving the screen as it is for you to see any error message.


call msbuild.bat
call unit-tests.bat
call deploy.bat

I know I am a bit late to the party, but here is another way. That is, this method should wait until the first one is done, the second, and so on.

start "" /wait cmd.exe /c msbuild.bat
start "" /wait cmd.exe /c unit-tests.bat
start "" /wait cmd.exe /c deploy.bat

The only issue that may come out of using this method, is that with new instances of cmd.exe being spawned, is that Errorlevel checking is kept within in each instance of cmd.exe.

Or..

start "" /wait call msbuild.bat
start "" /wait call unit-tests.bat
start "" /wait call deploy.bat

Hope this helps.


Run Multiple Batch Files Parallelly

start "systemLogCollector" /min cmd /k call systemLogCollector.bat
start "uiLogCollector" /min cmd /k call uiLogCollector.bat
start "appLogCollector" /min cmd /k call appLogCollector.bat

running-multiple-batch-files Here three batch files are run on separate command windows in a minimized state. If you don't want them minimized, then remove /min. Also, if you don't need to control them later, then you can get rid of the titles. So, a bare-bone command will be- start cmd /k call systemLogCollector.bat


If you want to terminate them-

taskkill /FI "WindowTitle eq appLogCollector*" /T /F
taskkill /FI "WindowTitle eq uiLogCollector*" /T /F
taskkill /FI "WindowTitle eq systemLogCollector*" /T /F

If you want to open many batch files at once you can use the call command. However, the call command closes the current bat file and goes to another. If you want to open many at once, you may want to try this:

@echo off
start cmd "call ex1.bat&ex2.bat&ex3.bat"

And so on or repeat start cmd "call..." for however many files. This works for Windows 7, but I am not sure about other systems.


Start msbuild.bat
Start unit-tests.bat
Start deploy.bat

If that doesn't work, replace start with call or try this:

Start msbuild.bat
Goto :1
:1
Start unit-tests.bat
Goto :2
:2
Start deploy.bat

Just use the call command! Here is an example:

call msbuild.bat
call unit-tests.bat
call deploy.bat

If we have two batch scripts, aaa.bat and bbb.bat, and call like below

call aaa.bat
call bbb.bat

When executing the script, it will call aaa.bat first, wait for the thread of aaa.bat terminate, and call bbb.bat.

But if you don't want to wait for aaa.bat to terminate to call bbb.bat, try to use the START command:

START ["title"] [/D path] [/I] [/MIN] [/MAX] [/SEPARATE | /SHARED]
  [/LOW | /NORMAL | /HIGH | /REALTIME | /ABOVENORMAL | /BELOWNORMAL]
  [/AFFINITY <hex affinity>] [/WAIT] [/B] [command/program]
  [parameters]

Exam:

start /b aaa.bat
start /b bbb.bat

using "&"

As you have noticed executing the bat directly without CALL,START, CMD /C causes to enter and execute the first file and then the process to stop as the first file is finished. Though you still can use & which will be the same as using command1 & command2 directly in the console:

(
    first.bat
)&(
    second.bat
)& (
    third.bat
)&(
    echo other commands
)

In a term of machine resources this will be the most efficient way though in the last block you won't be able to use command line GOTO,SHIFT,SETLOCAL.. and its capabilities will almost the same as in executing commands in the command prompt. And you won't be able to execute other command after the last closing bracket

Using CALL

call first.bat
call second.bat
call third.bat

In most of the cases it will be best approach - it does not create a separate process but has almost identical behaviour as calling a :label as subroutine. In MS terminology it creates a new "batch file context and pass control to the statement after the specified label. The first time the end of the batch file is encountered (that is, after jumping to the label), control returns to the statement after the call statement."

You can use variables set in the called files (if they are not set in a SETLOCAL block), you can access directly labels in the called file.

CMD /C, Pipes ,FOR /F

Other native option is to use CMD /C (the /C switch will force the called console to exit and return the control) Something that cmd.exe is doing in non transparent way with using FOR /F against bat file or when pipes are used. This will spawn a child process that will have all the environment ot the calling bat. Less efficient in terms of resources but as the process is separate ,parsing crashes or calling an EXIT command will not stop the calling .bat

@echo off
CMD /c first.bat
CMD /C second.bat

::not so different than the above lines.
:: MORE,FINDSTR,FIND command will be able to read the piped data 
:: passed from the left side

break|third.bat

START

Allows you more flexibility as the capability to start the scripts in separate window , to not wait them to finish, setting a title and so on. By default it starts the .bat and .cmd scripts with CMD /K which means that the spawned scripts will not close automatically.Again passes all the environment to the started scripts and consumes more resources than cmd /c:

:: will be executed in the same console window and will wait to finish
start "" /b /w cmd /c first.bat 

::will start in a separate console window and WONT wait to be finished
:: the second console window wont close automatically so second.bat might need explicit exit command
start "" second.bat

::Will start it in a separate window ,but will wait to finish
:: closing the second window will cause Y/N prompt
:: in the original window 
start "" /w third.cmd


::will start it in the same console window
:: but wont wait to finish. May lead to a little bit confusing output
start "" /b cmd /c fourth.bat

WMIC

Unlike the other methods from now on the examples will use external of the CMD.exe utilities (still available on Windows by default). WMIC utility will create completely separate process so you wont be able directly to wait to finish. Though the best feature of WMIC is that it returns the id of the spawned process:

:: will create a separate process with cmd.exe /c
WMIC process call create "%cd%\first.bat","%cd%"

::you can get the PID and monitoring it with other tools
for /f "tokens=2 delims=;= " %%# in ('WMIC process call create "%cd%\second.bat"^,"%cd%" ^|find "ProcessId"') do (
    set "PID=%%#"
)
echo %PID%

You can also use it to start a process on a remote machine , with different user and so on.

SCHTASKS

Using SCHTASKS provides some features as (obvious) scheduling , running as another user (even the system user) , remote machine start and so on. Again starts it in completely separate environment (i.e. its own variables) and even a hidden process, xml file with command parameters and so on :

SCHTASKS /create /tn BatRunner /tr "%cd%\first.bat" /sc ONCE /sd 01/01/1910 /st 00:00
SCHTASKS /Run /TN BatRunner
SCHTASKS /Delete /TN BatRunner /F

Here the PID also can acquired from the event log.

ScriptRunner

Offers some timeout between started scripts. Basic transaction capabilities (i.e. rollback on error) and the parameters can be put in a separate XML file.

::if the script is not finished after 15 seconds (i.e. ends with pause) it will be killed
ScriptRunner.exe -appvscript %cd%\first.bat -appvscriptrunnerparameters -wait -timeout=15


::will wait or the first called script before to start the second
:: if any of the scripts exit with errorcode different than 0 will try
:: try to restore the system in the original state
ScriptRunner.exe -appvscript second.cmd arg1 arg2 -appvscriptrunnerparameters -wait -rollbackonerror -appvscript third.bat -appvscriptrunnerparameters -wait -timeout=30 -rollbackonerror

All the other answers are correct: use call. For example:

 call "msbuild.bat"

History

In ancient DOS versions it was not possible to recursively execute batch files. Then the call command was introduced that called another cmd shell to execute the batch file and returned execution back to the calling cmd shell when finished.

Obviously in later versions no other cmd shell was necessary anymore.

In the early days many batch files depended on the fact that calling a batch file would not return to the calling batch file. Changing that behaviour without additional syntax would have broken many systems like batch menu systems (using batch files for menu structures).

As in many cases with Microsoft, backward compatibility therefore is the reason for this behaviour.

Tips

If your batch files have spaces in their names, use quotes around the name:

call "unit tests.bat"

By the way: if you do not have all the names of the batch files, you could also use for to do this (it does not guarantee the correct order of batch file calls; it follows the order of the file system):

FOR %x IN (*.bat) DO call "%x"

You can also react on errorlevels after a call. Use:

exit /B 1   # Or any other integer value in 0..255

to give back an errorlevel. 0 denotes correct execution. In the calling batch file you can react using

if errorlevel neq 0 <batch command>

Use if errorlevel 1 if you have an older Windows than NT4/2000/XP to catch all errorlevels 1 and greater.

To control the flow of a batch file, there is goto :-(

if errorlevel 2 goto label2
if errorlevel 1 goto label1
...
:label1
...
:label2
...

As others pointed out: have a look at build systems to replace batch files.


With correct quoting (this can be tricky sometimes):

start "" /D "C:\Program Files\ProgramToLaunch" "cmd.exe" "/c call ""C:\Program Files\ProgramToLaunch\programname.bat"""

1st arg - Title (empty in this case)
2nd arg - /D specifies starting directory, can be ommited if want the current working dir (such as "%~dp0")
3rd arg - command to launch, "cmd.exe"
4th arg - arguments to command, with doubled up quotes for the arguments inside it (this is how you escape quotes within quotes in batch)


If we want to open multiple command prompts then we could use

start cmd /k

/k: is compulsory which will execute.

Launching many command prompts can be done as below.

start cmd /k Call rc_hub.bat 4444

start cmd /k Call rc_grid1.bat 5555

start cmd /k Call rc_grid1.bat 6666

start cmd /k Call rc_grid1.bat 5570.

Running multiple scripts in one I had the same issue. I kept having it die on the first one not realizing that it was exiting on the first script.

:: OneScriptToRunThemAll.bat
CALL ScriptA.bat
CALL ScriptB.bat
EXIT

:: ScriptA.bat
Do Foo
EXIT
::ScriptB.bat
Do bar
EXIT

I removed all 11 of my scripts EXIT lines and tried again and all 11 ran in order one at a time in the same command window.

:: OneScriptToRunThemAll.bat
CALL ScriptA.bat
CALL ScriptB.bat
EXIT

::ScriptA.bat
Do Foo

::ScriptB.bat
Do bar