Bash flock Single-Instance Lock
Guarantee one cron job at a time with a flock file descriptor, a bounded wait, exit code 75, and cleanup that always unlocks.
Code
#!/usr/bin/env bash
set -euo pipefail
lock_file=${1:-"${TMPDIR:-/tmp}/devexamples-backup.lock"}
max_wait=${LOCK_WAIT_SECONDS:-5}
work_file=""
cleanup() {
local status=$?
if [[ -n "$work_file" && -f "$work_file" ]]; then
rm -f -- "$work_file"
fi
flock -u 9 2>/dev/null || true
exit "$status"
}
trap cleanup EXIT
exec 9>"$lock_file"
if ! flock -w "$max_wait" 9; then
printf 'could not acquire %s within %ss\n' "$lock_file" "$max_wait" >&2
exit 75
fi
printf 'lock acquired by pid %d\n' "$"
work_file="$(mktemp "${TMPDIR:-/tmp}/backup.XXXXXX")"
printf 'job %d started at %s\n' "$" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" > "$work_file"
sleep "${JOB_SECONDS:-1}"
cat -- "$work_file"
printf 'job %d finished; lock released on exit\n' "$"Inside the snippet
The shebang line is backed by set -euo pipefail: first failure stops the run, unset variables are errors, and a pipeline fails if any stage fails.
The work is delegated to rm, flock, trap, exec and sleep, chained through 2 pipes so each stage’s output feeds the next.
A helper function (cleanup) keeps the repeated logic out of the main flow.
The script leans on parameter expansion 4 times, using forms like ${var:-default} so defaults, trimming, and casing happen inside the shell with no external tool.
A trap handles termination signals so temporary state is cleaned up even on early exit.
The core lines, annotated
flock -u 9 2>/dev/null || true
exec 9>"$lock_file"
work_file="$(mktemp "${TMPDIR:-/tmp}/backup.XXXXXX")"
Interactive Tools for This Topic
FAQ
- Does the script stop on the first error?
- Yes — `set -euo pipefail` aborts on the first failing command, treats unset variables as errors, and fails the whole pipeline if any stage fails. Nothing continues half-broken.
- Which external commands does the script rely on?
- `rm`, `flock`, `trap`, `exec`, `sleep` must be available on the PATH environment variable; everything else is shell built-in syntax.
Report a problem with this exampleOpens a pre-filled issue on GitHub.