Friday, January 23, 2015

Running bash functions in parallel

I was blown away when I learned this. From this thread on stackoverflow it turns out that by simply adding an ampersand to a line containing a function call you can send it to run in the background!

#!/bin/bash
function foo {
  echo $1
  sleep $1
  date
}

for i in `seq 1 10`; do
  foo $i &
done

I always thought that this was restricted to programs/scripts you can call from the command line!

No comments:

Post a Comment