↑ ↓ select, Enter open, Esc close

Prevent overlapping cron jobs with flock

Adjust the values, the command updates live
user@server
flock -n /tmp/backup.lock /usr/local/bin/backup.sh

flock holds a lock on the lock file while the command runs, and -n aborts immediately if the lock is already taken. So if yesterday’s backup is still running, the new run does not start at all. In the crontab, simply put it in front of the actual command, for example 0 3 * * * flock -n /tmp/backup.lock /usr/local/bin/backup.sh.

Note: The lock is released automatically when the process ends or crashes, so a stale lock file does not block anything.

Also searched as

  • cron job running multiple times at once
  • prevent cron job overlap
  • lock file for cron job
  • run script only once at a time

Related one-liners

All in Cron

Read first, then run.

The commands on myline.de act directly on servers, files and databases. A wrong path or placeholder can delete data irreversibly or make a server unreachable.

  • All commands are provided without warranty and are not tested on every system.
  • Understand what a command does before running it, and check every placeholder.
  • Make a backup first and, if possible, try it on a test system.
  • You run commands at your own risk. Liability for damages is excluded to the extent permitted by law.