Skip to content

Instantly share code, notes, and snippets.

@gibatronic
Created October 26, 2018 12:58
Show Gist options
  • Save gibatronic/44faf43e260ec6a4d2daadcdce6aaaa0 to your computer and use it in GitHub Desktop.
Save gibatronic/44faf43e260ec6a4d2daadcdce6aaaa0 to your computer and use it in GitHub Desktop.
Proper job control in Bash scripts

Proper job control in Bash scripts

Simple example of how to properly launch background jobs and then gracefully terminate them.

Gotchas

  1. We could trap only the EXIT signal, but then after killing workers we get an unwanted "Terminated" message.
  2. In worker scripts, we must call exit when cleaning, to break out of the infinite loop
  3. After killing a worker, we still have to wait for them to gracefully terminate.

Further reading

#!/usr/bin/env bash
clean() {
echo
kill $(jobs -pr)
wait
echo 'main clean'
}
main() {
local self="$0"
local base="$(dirname "$self")"
trap 'clean' 'SIGINT' 'SIGTERM'
"$base/worker" 'A' &
"$base/worker" 'B' &
"$base/worker" 'C' &
wait
}
main "$@"
#!/usr/bin/env bash
clean() {
local name="$1"
echo "worker $name clean"
exit 0
}
main() {
local name="$1"
trap "clean '$name'" 'SIGINT' 'SIGTERM'
while true; do
sleep "$(($RANDOM % 5 + 1))"
echo "worker $name tick"
done
}
main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment