bash – collecting the return value of backgrounded processes

05 Dec

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"

3 Responses

  1. Agrion says:

    Nice, a very handy feature.

  2. alex says:

    thanks, this is very helpful :)

Leave a Reply

CodeWord: Apokalyptik

The random things that spew forth from my brain…