Skip to content

Instantly share code, notes, and snippets.

@mathew-fleisch
Last active May 20, 2025 06:16
Show Gist options
  • Save mathew-fleisch/fb5486f007f10c2d3d390ed563923f66 to your computer and use it in GitHub Desktop.
Save mathew-fleisch/fb5486f007f10c2d3d390ed563923f66 to your computer and use it in GitHub Desktop.
Bash threaded trap runtime example
#!/usr/bin/env bash
echo "starting a"
sleep 2
echo "completed a"
#!/usr/bin/env bash
echo "starting b"
sleep 3
echo "completed b"
# First time let it complete normally
$ ./wrapper.sh
starting: 1747721582
starting b
starting a
starting c
completed c
completed a
completed b
ended: 1747721585
Runtime: 00:00:03
# This time ctrl+c out of the script before it can finish
$ ./wrapper.sh
starting: 1747721637
starting a
starting b
starting c
^Cended: 1747721638
Runtime: 00:00:01
#!/usr/bin/env bash
echo "starting c"
sleep 1
echo "completed c"
#!/usr/bin/env bash
convertsecs() {
((h=${1}/3600))
((m=(${1}%3600)/60))
((s=${1}%60))
printf "%02d:%02d:%02d\n" $h $m $s
}
trapfunc() {
for pid in "${pids[@]}"; do
kill -9 $pid 2> /dev/null
done
end=$(date +%s)
echo "ended: $end"
diff=$((end - start))
echo "Runtime: $(convertsecs $diff)";
}
trap 'trapfunc $?; exit $?' EXIT
pids=()
start=$(date +%s)
echo "starting: $start"
./a.sh | tee output-a &
pids+=($!)
./b.sh | tee output-b &
pids+=($!)
./c.sh | tee output-c &
pids+=($!)
failed=0
for pid in "${pids[@]}"; do
wait $pid || { failed=1; break; }
done
if [ $failed -eq 1 ]; then
echo "A script failed while waiting."
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment