Copy-Paste Bash Backup Playbook

A woman using a laptop navigating a contemporary data center with mirrored servers.

Automate Your Backups in 5 Minutes

Need a simple, reliable backup script? Here’s a no-frills Bash playbook that:

  • Archives /var/www to a timestamped .tar.gz file
  • Rotates backups older than 7 days
  • Sends a log email on success or failure

Script:

#!/usr/bin/env bash
BACKUP_DIR="/backups"
SOURCE_DIR="/var/www"
TIMESTAMP=$(date '+%Y-%m-%d')
ARCHIVE="$BACKUP_DIR/www-$TIMESTAMP.tar.gz"

# Create backup directory if missing
mkdir -p "$BACKUP_DIR"

# Create archive
tar -czf "$ARCHIVE" "$SOURCE_DIR"

# Rotate old backups
find "$BACKUP_DIR" -type f -mtime +7 -name "*.tar.gz" -delete

# Send notification
if [[ $? -eq 0 ]]; then
  mail -s "Backup Success: $ARCHIVE" you@example.com <<< "Backup completed successfully."
else
  mail -s "Backup Failure" you@example.com <<< "Backup encountered an error."
fi

How to Use:

  • “Save as /usr/local/bin/backup-www.sh and chmod +x.”
  • “Add to cron: 0 2 * * * /usr/local/bin/backup-www.sh

There you have it… automated backups with rotation in under 5 minutes!

Automate /var/www backups with a simple Bash script that rotates old archives and notifies you by email.

Leave a Comment

Your email address will not be published. Required fields are marked *