flock Safety
flock is a Linux utility that acquires a file-based advisory lock before executing a command. It ensures that only one instance of a script runs at any given time, even if cron schedules overlapping runs.
Without flock safety, a long-running cron job (backup, report generation, data sync) can be scheduled to run every 5 minutes. If the job takes 7 minutes, by the 5-minute mark a second instance starts running concurrently. Both instances compete for the same resources, write to the same files, and produce corrupted output.
flock Syntax
Non-blocking (skip if already running): flock -n /tmp/jobname.lock /path/to/script.sh
Blocking (wait up to 10 seconds): flock -w 10 /tmp/jobname.lock /path/to/script.sh
In crontab: */5 * * * * flock -n /tmp/backup.lock /usr/local/bin/backup.sh
Lock File Placement
Lock files are typically placed in /tmp/ or /var/run/. The filename should be unique per job to avoid unrelated jobs blocking each other. /tmp/ is cleared on reboot, so stale locks from crashed scripts are automatically removed on next boot.
Related Tools
Fix Guides
Frequently Asked Questions
flock -n (non-blocking) for jobs that should skip if already running — backups, report generation, cleanup scripts. Use flock -w TIMEOUT for jobs that should wait — database migrations, deployment scripts where you want the next run to proceed once the current run finishes.