Interview Prep/Linux/Packages, Shell & Text Tools

How do you make sure only one instance of a cron script runs?

AdvancedConceptPackages, Shell & Text Tools
Answer

Use flock on a lock file; the kernel releases the lock automatically when the process dies, so there are no stale PID files.

*/5 * * * * /usr/bin/flock -n /run/lock/sync.lock /opt/scripts/sync.sh

Or inside the script:

exec 9>/run/lock/sync.lock
flock -n 9 || { echo "already running"; exit 0; }
All Linux questions Roadmap: Linux

More on Packages, Shell & Text Tools