anderson
anderson

Reputation: 51

Wait For Commands to Finish

I have a Windows batch file that starts other batch files. How do I wait for all the other batch files to finish before executing somthing in the first batch? I can't use /wait because I need the other commands to run in parallel.

Upvotes: 5

Views: 14671

Answers (2)

Aacini
Aacini

Reputation: 67206

You may use several flag files, one per running Batch file. For example:

First batch file create Flagfile.1 when enter, and delete it before end, and the same way the rest of concurrent batch files (Flagfile.2,...)

The main file just must wait for all flagfiles disappear. For example, in Main file:

start Batch1
start Batch2
.....
:wait
if exist flagfile.* goto wait

In any Batch file, for example Batch1:

echo %time% > flagfile.1
echo Do my process...
del flagfile.1
exit

Upvotes: 9

scrat.squirrel
scrat.squirrel

Reputation: 3826

My suggestion is to use CALL command. An example from Batch Files:

Batch1.bat listing:

REM Batch1.bat
SET ABC=1
CALL BATCH2.BAT %ABC%
ECHO ABC = %ABC%
BATCH2.BAT %ABC%
ECHO ABC = %ABC%

where Batch2.bat listing is:

REM Batch2.bat
SET ABC=%ABC%%1


EDIT: based on feedback from @Andriy M, here is an improved version for the two batches:

Batch 1:

@ECHO OFF
REM Batch1.bat
SET ABC=1
CALL batch2.bat %ABC%
ECHO 1. ABC = %ABC%
CALL batch2.bat %ABC% REM test this line with CALL and without
ECHO 2. ABC = %ABC%

Batch 2:

@ECHO OFF
REM Batch2.bat
SET tmout=5
echo sleeping %tmout% seconds...
REM this introduces a timeout by using a nonexistent ip address
PING 1.2.1.2 -n 1 -w %tmout%000 > NUL
echo done sleeping
SET ABC=%ABC%%1

See the line in batch1 where I wrote the comment test this line with CALL and without. Run that batch twice, with that line having CALL and without CALL.

The output from console without CALL:

C:\temp>batch1.bat
sleeping 5 seconds...
done sleeping
1. ABC = 11
sleeping 5 seconds...
done sleeping

And now the output from console with CALL:

C:\temp>batch1.bat
sleeping 5 seconds...
done sleeping
1. ABC = 11
sleeping 5 seconds...
done sleeping
2. ABC = 1111

Please note the difference: we get the 2nd echo, q.e.d.

Upvotes: 1

Related Questions