shBash
AdvancedLesson 15 of 15

Automation with cron & a Practical Project – Bash

Run scripts on a schedule: crontab syntax, environment, logs and locks.

cron starts commands on a schedule. You edit the table with crontab -e and display it with crontab -l. Each line has five time fields and the command: minute hour day-of-month month day-of-week (0 or 7 = Sunday).

# ┌ Minute (0-59)
# │ ┌ Hour (0-23)
# │ │ ┌ Day of month (1-31)
# │ │ │ ┌ Month (1-12)
# │ │ │ │ ┌ Day of week (0-7, 0/7 = Sun)
# │ │ │ │ │
  0 2 * * *       /home/ada/bin/backup.sh /home/ada/projekte /backups   # daily at 02:00
  */15 * * * *    /home/ada/bin/check.sh                                  # every 15 minutes
  30 8 * * 1-5    /home/ada/bin/report.sh                                 # Mon–Fri at 08:30
  0 0 1 * *       /home/ada/bin/monatsabschluss.sh                        # on the 1st of every month
  @reboot         /home/ada/bin/start-dienst.sh                           # at system startup

Cron runs with a minimal environment: a short PATH, no terminal, a different working directory. Therefore: use absolute paths, redirect output to a log file and set PATH yourself. If a job runs longer than its interval, flock prevents overlaps.

# in the crontab, at the top:
SHELL=/bin/bash
PATH=/usr/local/bin:/usr/bin:/bin
MAILTO=""                    # no emails on output

*/5 * * * * flock -n /tmp/check.lock /home/ada/bin/check.sh >> /home/ada/logs/check.log 2>&1

# Test: run the script exactly like cron (empty environment)
env -i SHELL=/bin/bash PATH=/usr/bin:/bin /home/ada/bin/check.sh

Practical example: a script that checks disk usage and warns when a threshold is exceeded – well suited for a cron entry.

#!/usr/bin/env bash
set -euo pipefail
schwelle="${1:-80}"
# df -P: portable output; awk gets the usage (column 5) of the root; tr removes the %-sign
belegung=$(df -P / | awk 'NR == 2 { print $5 }' | tr -d '%')
if (( belegung >= schwelle )); then
  echo "WARNING: / is $belegung% full (threshold: $schwelle%)" >&2
  exit 1
fi
echo "OK: / is $belegung% full"
WarningOn macOS, newer versions require "Full Disk Access" for /usr/sbin/cron, and flock is missing there by default; for Mac automation launchd (~/Library/LaunchAgents/*.plist) is the native way, on Linux servers increasingly systemd timers. Also: % has a special meaning in crontab lines – write \% (e.g. with date +\%F).
TipTest order: (1) run the script manually, (2) with env -i in an empty environment, (3) trial-run the cron line with a short interval (* * * * *), (4) check the log, (5) adjust the interval. And always plan for log rotation (logrotate).