I want to execute the commands in a loop at the same time, not one after another

I'd like to write a loop ('for') that will do some action 'X' number of times. But instead of performing the actions sequentially, one after another, I'd like them to execute simultaneously (in parellel at the same time). How can this be achieved? Script or a one liner are fine.

example ONLY:

for i in 1 2 3 4 5; do dd if=/dev/zero of=/tmp/disk$i bs=10M count=10; done

Solution 1:

This is mostly along the answer Dennis gave (+1 there), with your sample case.

for i in $(seq 1 5); do \
 dd if=/dev/zero of=/tmp/disk$i bs=10M count=10 & \
done; wait

the '\' and new lines are just for reading-pleasure, you can write all that in one line.


This gives a better understanding of the control sequence and syntax,

for i in $(seq 1 5); do \
 ( \
  echo "$i starting ..."; \
  dd if=/dev/zero of=/tmp/disk$i bs=10M count=10; \
  echo "$i done ..."; \
 ) & \
done; wait

Solution 2:

Add an ampersand (&) at the end of the dd command to make each one run in the background and add ; wait after the done.

In some cases, xargs --max-args=MAX-ARGS --max-procs=MAX-PROCS can be used.

Solution 3:

If you have GNU Parallel http:// www.gnu.org/software/parallel/ installed you can do this:

seq 1 5 | parallel dd if=/dev/zero of=/tmp/disk{} bs=10M count=10

Watch the intro video for GNU Parallel to learn more: http://www.youtube.com/watch?v=OpaiGYxkSuQ