Archive for December 5th, 2008

bash – collecting the return value of backgrounded processes

Bash, Business, CLI, Linux, Random Thoughts, Software Development | Posted by apokalyptik
Dec 05 2008

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"