Interview Prep/Shell Scripting/Scenarios: backups, log rotation and housekeeping

A backup job sometimes runs twice at the same time and the archives are corrupted. How do you prevent it?

BeginnerScenarioScenarios: backups, log rotation and housekeeping
Answer

Situation read → A slow run overlaps with the next scheduled one, or someone ran it manually during the scheduled run.

What I'd do →

  1. Take an exclusive lock at the top of the script:
    exec 9>/run/lock/backup.lock
    flock -n 9 || { echo "backup already running, skipping" >&2; exit 0; }
    
  2. Write to unique temp names and mv into place, so even an unexpected overlap cannot interleave writes.
  3. If migrating to systemd timers, systemd will not start a service that is already running.

Why → flock locks are released by the kernel when the process dies, so there are no stale lock files after a crash.

Interview tip → Explain why PID files are worse: they go stale after kill -9, and PIDs get reused.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Scenarios: backups, log rotation and housekeeping