Prevent Overlapping Runs With flock
Take a file lock so a cron job cannot start while the previous run is active.
Run flock -n /tmp/job.lock command to run the command only if no other run holds the lock.
01Command
Command
$ flock -n /tmp/backup.lock /usr/local/bin/backup.sh02What it does
flock wraps a command in an advisory file lock, so a long backup or sync invoked by cron will not pile up if the previous run overruns. This is a core reason to script recurring work: scheduling and concurrency control belong in the terminal.
03Risk
!Warning: flock is a util-linux tool; macOS does not ship it by default and needs coreutils via Homebrew.
04Undo
✓No undo needed — this command does not change persistent state.
05Sources
- flock.1.en.html manual pageEvidence: Documents flock -n, which fails immediately if the lock is held.
- flock(1) — Linux manual pageEvidence: Documents file locking from shell scripts with flock.
Last verified: 2026-10-13 · Category: Developer