Interview Prep/Shell Scripting/cron and systemd timers

How do you prevent overlapping cron runs and capture output properly?

IntermediateConceptcron and systemd timers
Answer
*/5 * * * * flock -n /run/lock/sync.lock /opt/scripts/sync.sh >> /var/log/sync.log 2>&1
  • flock -n skips the run if the previous one still holds the lock.
  • >> file 2>&1 keeps both streams; better still, log through logger -t sync so output lands in syslog/journald.
  • Add timeout 4m if a hung run should be killed before the next slot.

Without a lock, a job that occasionally runs longer than its interval piles up copies and can exhaust memory or corrupt data.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on cron and systemd timers