Skip to content

Instantly share code, notes, and snippets.

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)
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

This comment has been minimized.

Copy link

@silenc3r silenc3r commented May 21, 2020

I don't think trap "exit" INT TERM is needed. It suppresses the real exit code causing the script to always exit with success (exit 0).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment