Prevent Overlapping Runs With flock

Take a file lock so a cron job cannot start while the previous run is active.

macOSbashautomationshellscriptingLow risk
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.sh

02What 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

RiskLow risk
RequirementsmacOS default zsh/bash (bash 3.2+; some features need bash 4+ via Homebrew)
CompatibilitymacOS with bash 3.2+ (GNU bash 4+ via Homebrew for advanced features)
!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

Last verified: 2026-10-13 · Category: Developer