BASH

Automate Website Directory Backup with Tar and Gzip

Learn how to create a Bash script to automate daily backups of your website directory, compressing them with tar and gzip for efficient storage and management.

#!/bin/bash
# Configuration
BACKUP_DIR="/var/www/mywebsite" # Directory to backup
DEST_DIR="/backups/website"    # Destination for backup files
DATE=$(date +"%Y%m%d%H%M%S")  # Timestamp for backup file
BACKUP_FILENAME="website_backup_${DATE}.tar.gz"

# Create destination directory if it doesn't exist
mkdir -p "$DEST_DIR"

# Create the backup
echo "Starting backup of $BACKUP_DIR..."
tar -czf "$DEST_DIR/$BACKUP_FILENAME" -C "$(dirname "$BACKUP_DIR")" "$(basename "$BACKUP_DIR")"

if [ $? -eq 0 ]; then
    echo "Backup successful: $DEST_DIR/$BACKUP_FILENAME"
    # Optional: Remove backups older than 7 days
    find "$DEST_DIR" -type f -name "website_backup_*.tar.gz" -mtime +7 -delete
    echo "Old backups removed."
else
    echo "Backup failed!"
    exit 1
fi
How it works: This script automates the backup process for a specified website directory. It uses `tar` with the `-c` (create), `-z` (gzip compress), and `-f` (file) options to archive and compress the directory. A timestamp is added to the filename for easy identification. After a successful backup, it optionally removes old backup files older than 7 days using `find` to manage disk space, which is crucial for server maintenance.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs