bash – collecting the return value of backgrounded processes

You know that you can run something in the background in a bash script with ( command )&, but a coworker recently wanted to run multiple commands, wait for all of them to complete, collect and decide what to do based on their return values… this proved much trickier. Luckily there is an answer

#!/bin/bash

(sleep 3; exit 1)& p1=$!
(sleep 2; exit 2)& p2=$!
(sleep 1; exit 3)& p3=$!

wait "$p1"; r1=$?
wait "$p2"; r2=$?
wait "$p3"; r3=$?

echo "$p1:$r1 $p2:$r2 $p3:$r3"

Comments (3)

  1. meathive wrote::

    Neat.

    Saturday, December 6, 2008 at 7:20 AM #
  2. Agrion wrote::

    Nice, a very handy feature.

    Wednesday, April 8, 2009 at 3:20 AM #
  3. alex wrote::

    thanks, this is very helpful :)

    Saturday, March 13, 2010 at 11:54 AM #