WEBTOOLIST.
STATIC WEB PLATFORM
NO ACCOUNTS / NOTHING TO INSTALL

$ webtoolist --script cron-wrapper

Cron Wrapper with Locking

Run a command from cron with a lock, timestamped log, and exit status.

category Automation shell Bash 4+ updated 2026-08-31
cronlockautomationlogging
Safety notes
  • Executes the command you pass to it — review the crontab line before enabling.
  • The lock prevents overlapping runs; it does not retry failed work.

Dependencies: flock, date

Usage

  • Pass a log name and the command to run.
  • Point the crontab at this script, not at the command directly.

Script

#!/usr/bin/env bash
set -euo pipefail

name="${1:-}"
shift || true
(($# > 0)) || { echo "usage: $0 NAME COMMAND [ARGS...]" >&2; exit 1; }

log_dir="${LOG_DIR:-$HOME/.local/state/cron}"
mkdir -p "$log_dir"
log="$log_dir/$name.log"
lock="$log_dir/$name.lock"

exec 9>"$lock"
if ! flock -n 9; then
  echo "$(date -Is) already running; skipping" >> "$log"
  exit 0
fi

{
  echo "=== $(date -Is) start: $* ==="
  "$@"
  status=$?
  echo "=== $(date -Is) end: status=$status ==="
} >> "$log" 2>&1

exit "${status:-0}"

Example

./cron-wrapper nightly-backup rsync -a /data/ /mnt/backup/data/
# crontab: 15 2 * * * /usr/local/bin/cron-wrapper nightly-backup /usr/local/bin/backup.sh

Notes

  • flock -n returns immediately when a previous run still holds the lock.
  • Logs grow forever; pair this with the log cleanup script or logrotate.

Related scripts

Batch Command Runner

Run one command on a list of SSH hosts, sequentially, with clear output.

Automation