Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Run some commands asynchronously in bash and then make sure to kill the child processes if the user kills the process with CTRL-C (or similar)
#!/bin/bash
trap "exit" INT TERM # Convert INT and TERM to EXIT
trap "kill 0" EXIT # Kill all children if we receive EXIT
# Run stuff in the background
sleep 3 &
sleep 4 &
# Find child processes and wait for them to finish so this script doesn't
# exit before the children do (otherwise our trap will kill them)
for job in $(jobs -p); do
wait $job
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.