Introduction
Rsync is a fast, versatile file synchronization tool built into most Linux distributions. Combined with cron, it creates a reliable automated backup solution for your server.
Basic Rsync Syntax
rsync -avz --delete /source/directory/ /backup/directory/Key flags:
-a— archive mode (preserves permissions, timestamps, symlinks)-v— verbose output-z— compress data during transfer--delete— remove files from destination that no longer exist in source
Remote Backup Script
#!/bin/bash
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
LOG="/var/log/backup_${TIMESTAMP}.log"
rsync -avz --delete \
-e "ssh -p 22 -i /root/.ssh/backup_key" \
/var/www/ \
/etc/ \
/home/ \
backupuser@remote-server:/backups/$(hostname)/ \
>> "$LOG" 2>&1
echo "Backup completed: $(date)" >> "$LOG"Scheduling with Cron
# Daily backup at 3 AM
0 3 * * * /root/scripts/backup.shExclude Patterns
Create an exclude file to skip unnecessary data:
# /root/scripts/backup-exclude.txt
*.log
*.tmp
/var/cache/*
/tmp/*
node_modules/Add --exclude-from=/root/scripts/backup-exclude.txt to your rsync command.