Skip to content

Instantly share code, notes, and snippets.

@heydonovan
Created November 21, 2014 01:13
Show Gist options
  • Save heydonovan/bddbb230618bb5d889cc to your computer and use it in GitHub Desktop.
Save heydonovan/bddbb230618bb5d889cc to your computer and use it in GitHub Desktop.
#!/bin/bash
set -o pipefail
LOCK_NAME="$1"
COMMAND_TO_RUN="$2"
cleanUp() {
flock -u 200
}
# run the cleanUp function if the script is killed or dies
trap cleanUp EXIT
# create a new file descriptor and point it to a unique file
exec 200>/var/run/cron-${LOCK_NAME} || exit 1
# invoke the lock on the new file descriptor
flock -n 200 || { logger -t "FLOCK" "Could not unlock ${LOCK_NAME}"; exit 1; }
# commands to be run under lock
# the first part logs stderr to logger, tagging each line as an error
# the second part logs the name of the cron job, so we can see the number of per-cron errors
eval $COMMAND_TO_RUN 2>&1 >/dev/null | logger -t "ERROR" || { logger -t "ERROR" "The ${LOCK_NAME} process returned a non-zero exit code"; exit 1; }
# release the lock
flock -u 200
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment