Prevent overlapping runs with a file lock
Bash
#!/usr/bin/env bash
# Prevent overlapping cron runs with an exclusive flock on fd 9 (Linux).
set -euo pipefail
lock_file="${LOCK_FILE:-/tmp/nightly-report.lock}"
mkdir -p -- "$(dirname -- "$lock_file")"
# Open the lock file and take a non-blocking exclusive lock.
exec 9>"$lock_file"
if ! flock -n 9; then
printf 'another run is active, exiting\n' >&2
exit 0
fi
printf 'started %s\n' "$(date -u +%FT%TZ)"
# Do the real work here; it must not close fd 9.
sleep 3
printf 'finished %s\n' "$(date -u +%FT%TZ)"