Automating Linux Server Backups with Systemd Timers and Bash
While cron has long been the default utility for scheduling systemic tasks, modern deployments benefit significantly from migrating to native systemd timer units. Systemd provides granular microsecond dependency controls, robust execution sandboxing, and direct cgroups telemetry routed to journald.
1. The Core Backup Payload Script
First, compile an isolated administrative backup script under /usr/local/bin/backup-srv.sh. This handles target payload compaction and local retention rotation rules.
#!/usr/bin/env bash
set -euo pipefail
BACKUP_DIR="/var/backups/infra"
TARGET_SOURCE="/var/www/html"
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
mkdir -p "$BACKUP_DIR"
echo "Starting system synchronization..."
tar -czf "$BACKUP_DIR/backup_$TIMESTAMP.tar.gz" "$TARGET_SOURCE"
# Purge any historical assets older than 14 days
find "$BACKUP_DIR" -type f -name "backup_*.tar.gz" -mtime +14 -delete
echo "Backup cycle completed successfully."
2. Configuring the Systemd Service Unit
Construct a dedicated service unit configuration block mapping to our script runtime context. Save this profile into /etc/systemd/system/backup-infra.service.
[Unit]
Description=Automated Infrastructure Backup Payload
After=network.target
[Service]
Type=oneshot
ExecStart=/usr/local/bin/backup-srv.sh
User=root
PrivateTmp=true
ProtectSystem=full
3. Initializing the Systemd Timer Block
Finally, we link the service unit explicitly to a calendar event frequency block. Establish /etc/systemd/system/backup-infra.timer to run early every morning.
[Unit]
Description=Trigger Backup Infrastructure Unit Daily
[Timer]
OnCalendar=*-*-* 04:30:00
Persistent=true
[Install]
WantedBy=timers.target
Apply the unit modifications and enable the routine via administrative hooks:
systemctl daemon-reload
systemctl enable --now backup-infra.timer