lightweight
lightweight

Reputation: 3327

run for each loop in parallel

if I have a for each statement like this:

for i in 1 2 3 4
do
    fairly large script here with lots of logic and stuff and $i is in many areas..the code in ehre also needs to run in a sequence...
done

how can I spawn the 4 loops in parallel and not run in serial

Upvotes: 0

Views: 325

Answers (2)

Mark Setchell
Mark Setchell

Reputation: 207425

I think I understand what you mean now. You want 4 pairs of jobs to run in parallel and the 2 halves of each pair need to run sequentially. So, in essence, you have

Job 1A followed sequentially by Job 1B
Job 2A followed seuqentially by Job 2B
Job 3A followed sequentially by Job 3B
Job 4A followed sequentially by Job 4B

and the 4 lines above can all be run in parallel.

If that is the case, you need:

for i in 1 2 3 4 ; do 
   ( echo $i A start; sleep 5; echo $i A end; echo $i B start; sleep 5; echo $i B end ) &  
done

Upvotes: 1

Gilles Quénot
Gilles Quénot

Reputation: 185025

With the & operator (run in background)

for i in 1 2 3 4
do
    echo "test 1 $i" &
    echo "test 2 $i" &
done

Upvotes: 0

Related Questions