Last active
May 7, 2021 23:38
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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
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).