I'm trying to write a "while true" bash script that responds to events. (It's a webhook for git push notifications, but that's not very relevant at this point.)
I could block, waiting for the next callback, run the build, and then block again, but if I get a callback in the middle of the build, I'd miss that, so instead I'm trying to solve it as follows:
# Build loop, run in the background (see "done &" at the bottom) while true do # If last build start is newer than last push do nothing. if [ last-build-start -nt last-push ] then echo "last-build-start newer than last-push. Doing nothing." sleep 3 continue fi log "Build triggered $(date)" touch last-build-start ./build-all-branches.sh log "Done. Waiting for next trigger..." done & # Terminate above loop upon Ctrl+C trap "trap - SIGTERM && kill -- -$$" SIGINT SIGTERM EXIT # Listen for HTTP requests, do nothing but touch last-push # to trigger a build in the build loop above. while true do # Wait for hook to be called echo -e "HTTP/1.1 200 OK\n\n $(date)" \ | nc -l 8787 -q 1 > /dev/null # Trigger new build echo "Triggered... touching last-push" touch last-push done
The problem I'm experiencing is that the build-loop is not always triggered. The
touch last-push is executed, but it's just as if another instance of the build loop is kicking in and executing
touch last-build-start in a racy way.
Am I accidentally kicking off more than one build loop in the above code? Is there any other silly mistake in the script?