BASH

Create Timestamped Directory Backups

Generate compressed, timestamped backups of important directories like website content or configurations using `tar`, ensuring easy restoration and versioning control.

#!/bin/bash

# Configuration variables
SOURCE_DIR="/var/www/html/mywebsite"   # Directory to be backed up
BACKUP_DIR="/backups/mywebsite_data"   # Directory where backups will be stored
TIMESTAMP=$(date +%Y%m%d_%H%M%S)       # Generates a timestamp (e.g., 20231027_143000)
BACKUP_FILENAME="mywebsite_backup_$TIMESTAMP.tar.gz" # Full backup filename
RETENTION_DAYS=7                       # Number of days to keep old backups

# Create the backup directory if it doesn't exist
mkdir -p "$BACKUP_DIR"

echo "Starting backup of $SOURCE_DIR to $BACKUP_DIR/$BACKUP_FILENAME..."

# Create the compressed tar archive
# -c: create archive
# -z: compress with gzip
# -f: specify archive filename
# -C: change to directory before adding files (important for relative paths within archive)
# "$(basename "$SOURCE_DIR")": adds the directory name itself, not its parent
tar -czf "$BACKUP_DIR/$BACKUP_FILENAME" -C "$(dirname "$SOURCE_DIR")" "$(basename "$SOURCE_DIR")"

# Check the exit status of tar
if [ $? -eq 0 ]; then
    echo "Backup completed successfully: $BACKUP_DIR/$BACKUP_FILENAME"
    
    echo "Cleaning up old backups (older than $RETENTION_DAYS days)..."
    # Find and delete backups older than RETENTION_DAYS
    find "$BACKUP_DIR" -type f -name "mywebsite_backup_*.tar.gz" -mtime +$RETENTION_DAYS -delete
    if [ $? -eq 0 ]; then
        echo "Old backups cleaned up successfully."
    else
        echo "Warning: Failed to clean up old backups."
    fi
else
    echo "Backup failed. Please check permissions or path."
    exit 1
fi
How it works: This script creates a compressed, timestamped backup of a specified directory using the `tar` command. This is essential for regularly safeguarding website files, configuration data, or databases. The script also includes an optional cleanup routine that automatically deletes backups older than a configurable number of days, helping manage disk space and adhere to retention policies.

Need help integrating this into your project?

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

Hire DigitalCodeLabs