Home / Linux / How to Create Automatic Backups with cron + rsync

How to Create Automatic Backups with cron + rsync

Automate file backups on a Linux VPS using rsync and cron: create a script, test it, log output, and verify backups safely.

Views: 24 Unique: 19 Updated: 2026-03-21

What this is

This guide shows how to create automatic backups using rsync (file copy with sync) and cron (scheduler).

What it is for

  • Daily backups of important folders (websites, configs)
  • Quick recovery after mistakes
  • Better discipline than manual backups

Prerequisites

  • SSH + sudo
  • A backup destination (recommended: another server or mounted storage)
  • Enough disk space for backups

Step-by-step

Step 1) Install rsync (if needed)

Ubuntu/Debian:

sudo apt update
sudo apt install -y rsync

RHEL-based:

sudo dnf install -y rsync

Step 2) Create a local backup folder

sudo mkdir -p /var/backups/rsync
sudo chown -R $USER:$USER /var/backups/rsync

Step 3) Create a backup script

mkdir -p ~/scripts ~/logs
nano ~/scripts/backup_rsync.sh

Example script (backup /etc and /var/www):

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

TS=$(date +%F)
DEST=/var/backups/rsync/$TS

mkdir -p "$DEST"

rsync -aH --delete /etc/ "$DEST/etc/"
rsync -aH --delete /var/www/ "$DEST/var_www/"

echo "Backup completed: $DEST"

What each rsync flag does:

  • -a: archive mode (preserves permissions, times, symlinks)
  • -H: preserve hard links (useful for some layouts)
  • --delete: removes files in destination that no longer exist in source (keeps mirror)

Warning: --delete is powerful. Make sure source/destination paths are correct.

Step 4) Make the script executable

chmod +x ~/scripts/backup_rsync.sh

Step 5) Test it manually (before cron)

~/scripts/backup_rsync.sh

Expected output: A line like Backup completed: /var/backups/rsync/2026-02-08.

Step 6) Add cron job (daily at 2:30 AM)

crontab -e

Add this line:

30 2 * * * /usr/bin/bash /home/USERNAME/scripts/backup_rsync.sh >> /home/USERNAME/logs/backup_rsync.log 2>&1

What it does: Runs the script daily and logs output.

Final verification

crontab -l
ls -la /var/backups/rsync
tail -n 50 ~/logs/backup_rsync.log

Conclusion

You now have automated backups. Next step: copy backups off-server (recommended) and test restores.

Back to category