How Can We Help?
Creating System Backups with rsync
Tutorial Overview
This tutorial provides a comprehensive guide to using rsync for creating backups of important files and directories. rsync is a powerful and flexible tool that enables efficient file synchronization and backup.
Prerequisites
- Root or sudo access.
- Ensure you have enough disk space on the destination storage (another directory, external drive, or remote server).
Steps
Step 1: Install rsync
1. Confirm if rsync is installed:
rsync --version
2. If not installed, use:
sudo apt update
sudo apt install rsync -y
Step 2: Basic rsync
Command for Local Backups
1. Back up a specific directory (e.g., /home/user/documents) to a backup location (e.g., /backup/documents_backup):
sudo rsync -a /home/user/documents /backup/documents_backup
- The -a option stands for “archive,” which preserves permissions, ownership, and timestamps, and copies directories recursively.
2. Verify the Backup:
- Check if the files are copied correctly:
ls /backup/documents_backup
Step 3: Perform an Incremental Backup
1. To only back up files that have changed since the last backup, use:
sudo rsync -a --update /home/user/documents /backup/documents_backup
- The –update option ensures only newer or modified files are copied, saving time and space.
Step 4: Back Up to a Remote Server
1. To back up files to a remote server with SSH (replace user, remote_host, and /remote/backup with your details):
sudo rsync -a -e ssh /home/user/documents user@remote_host:/remote/backup
2. Test the SSH Connection:
- Ensure that you can connect without being prompted for a password by setting up SSH keys.
Step 5: Automate Backups with a Script
- Create a script file, backup_script.sh:
sudo nano /usr/local/bin/backup_script.sh
2. Add the following script contents:
#!/bin/bash
rsync -a --delete /home/user/documents /backup/documents_backup
echo "Backup completed on $(date)" >> /backup/backup.log
- The –delete option removes files from the destination if they no longer exist in the source, keeping the backup location consistent.
3. Make the Script Executable:
sudo chmod +x /usr/local/bin/backup_script.sh
4. Schedule the Script with Cron:
- Edit the crontab file:
crontab -e
- Add an entry to run the script every night at 2:00 AM:
0 2 * * * /usr/local/bin/backup_script.sh