Skip to content

Instantly share code, notes, and snippets.

@jiaaro
Last active May 7, 2021 23:38
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jiaaro/b2e1b7c705022c2cf56888152a999f65 to your computer and use it in GitHub Desktop.
Save jiaaro/b2e1b7c705022c2cf56888152a999f65 to your computer and use it in GitHub Desktop.
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
@silenc3r
Copy link

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