Build a System Backup Script

Summary: Create a full system or folder backup utility.


Data loss can be catastrophic, whether due to hardware failure, malware, or accidental deletion. Reliable backups are essential for any system, professional or personal. In this guide, we’ll walk through building a robust backup script, capable of archiving specific folders or your entire system efficiently.

Why Automate Backups?

Manual backups are prone to human error and often forgotten until it’s too late. By automating the process, you ensure consistency, minimize risk, and make disaster recovery far less stressful.

Requirements

Our backup script will:

  • Archive desired folders or the entire filesystem
  • Timestamp each backup to prevent overwrites
  • Store backups in a defined location (local or remote)
  • Optionally, compress backups to save space
  • Offer an option for incremental backups
  • Log operations for troubleshooting

We’ll use Bash on Linux for demonstration, though similar logic applies to macOS (and PowerShell can work for Windows).

Step 1: Define Backup Parameters

Let's begin by setting up variables at the top of our script.
Create a file named backup.sh:

#!/bin/bash

# === User Configuration ===
BACKUP_SRC="/home/user /etc /var/www"
BACKUP_DEST="/mnt/backup/system"
LOG_FILE="/var/log/backup_script.log"
DATE=$(date +'%Y-%m-%d_%H-%M-%S')
HOSTNAME=$(hostname)
BACKUP_NAME="${HOSTNAME}_backup_${DATE}.tar.gz"

# Retain last 7 backups
RETENTION=7

# Exclude certain files/directories (optional)
EXCLUDES="--exclude=/home/user/.cache --exclude=/proc --exclude=/sys"
  • Adjust BACKUP_SRC to include folders you wish to backup.
  • Change BACKUP_DEST to your backup storage location.

Step 2: Archive Data

We’ll use tar to gather & compress files:

echo "[$(date)] Starting backup..." >> "$LOG_FILE"
tar czpf "${BACKUP_DEST}/${BACKUP_NAME}" $EXCLUDES $BACKUP_SRC 2>> "$LOG_FILE"
if [[ $? -eq 0 ]]; then
    echo "[$(date)] Backup successful: $BACKUP_NAME" >> "$LOG_FILE"
else
    echo "[$(date)] Backup failed!" >> "$LOG_FILE"
    exit 1
fi

This command creates a compressed archive and logs errors.

Explanation

  • c — create archive
  • z — compress with gzip
  • p — preserve permissions
  • f — filename
  • $EXCLUDES — skip specified dirs

Step 3: Manage Old Backups

Automatically purge old backups to save space:

echo "[$(date)] Cleaning old backups..." >> "$LOG_FILE"
ls -1t "${BACKUP_DEST}"/${HOSTNAME}_backup_*.tar.gz | tail -n +$((RETENTION+1)) | xargs -r rm --

This keeps only the most recent $RETENTION backups.

Step 4: Automate with Cron

To create regular backups, add a cron job:

crontab -e

Add the following (daily at 3AM):

0 3 * * * /path/to/backup.sh

Step 5: (Optional) Incremental Backups

For large datasets, incremental backups are more efficient. Use rsync:

rsync -aAXv --delete $BACKUP_SRC "$BACKUP_DEST/latest/" >> "$LOG_FILE" 2>&1

Change latest to timestamped dirs if you want snapshots.

Full Script Example

Here's the complete backup script:

#!/bin/bash

# === Configuration ===
BACKUP_SRC="/home/user /etc /var/www"
BACKUP_DEST="/mnt/backup/system"
LOG_FILE="/var/log/backup_script.log"
DATE=$(date +'%Y-%m-%d_%H-%M-%S')
HOSTNAME=$(hostname)
BACKUP_NAME="${HOSTNAME}_backup_${DATE}.tar.gz"
RETENTION=7
EXCLUDES="--exclude=/home/user/.cache --exclude=/proc --exclude=/sys"

mkdir -p "$BACKUP_DEST"

echo "[$(date)] Starting backup..." >> "$LOG_FILE"
tar czpf "${BACKUP_DEST}/${BACKUP_NAME}" $EXCLUDES $BACKUP_SRC 2>> "$LOG_FILE"
if [[ $? -eq 0 ]]; then
    echo "[$(date)] Backup successful: $BACKUP_NAME" >> "$LOG_FILE"
else
    echo "[$(date)] Backup failed!" >> "$LOG_FILE"
    exit 1
fi

# Retention policy
echo "[$(date)] Cleaning old backups..." >> "$LOG_FILE"
ls -1t "${BACKUP_DEST}"/${HOSTNAME}_backup_*.tar.gz | tail -n +$((RETENTION+1)) | xargs -r rm --

echo "[$(date)] Backup script completed" >> "$LOG_FILE"

Make it executable:

chmod +x backup.sh

Additional Enhancements

  • Email Alerts: Use mail to notify you of failures.
  • Remote Backups: Use scp or rsync to upload to another server.
  • Encryption: Pipe your tar output through gpg for secure backups.
  • Restore: Use tar xzpf /path/to/backup.tar.gz to extract backups.

Conclusion

By building a system backup script, you take a significant step toward securing your data and ensuring business continuity. With customization and periodic review, your backups will remain reliable and effective—making recovery straightforward when you need it most.


Tip: Always test both your backup and restore process. A backup is only as good as your ability to recover from it!