← Back to all snippets
BASH

Backup a Directory with Timestamp and Retention

Create timestamped backups of a specified directory, compressing them and automatically deleting old backups to manage disk space efficiently.

#!/bin/bash

# --- Configuration ---
BACKUP_DIR="/path/to/your/website"
DEST_DIR="/path/to/backup/storage"
RETENTION_DAYS=7 # Keep backups for 7 days

# --- Script Logic ---

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

# Generate timestamp for the backup file
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
BACKUP_FILENAME="website_backup_${TIMESTAMP}.tar.gz"

echo "Starting backup of $BACKUP_DIR to $DEST_DIR/$BACKUP_FILENAME"

# Create the gzipped tar archive
tar -czf "$DEST_DIR/$BACKUP_FILENAME" -C "$(dirname "$BACKUP_DIR")" "$(basename "$BACKUP_DIR")"

if [ $? -eq 0 ]; then
  echo "Backup created successfully: $BACKUP_FILENAME"
else
  echo "Error creating backup." >&2
  exit 1
fi

# Clean up old backups based on retention policy
echo "Cleaning up old backups (older than $RETENTION_DAYS days) in $DEST_DIR..."
find "$DEST_DIR" -name "website_backup_*.tar.gz" -type f -mtime +$RETENTION_DAYS -delete

if [ $? -eq 0 ]; then
  echo "Old backups cleaned up successfully."
else
  echo "Error cleaning up old backups." >&2
fi

echo "Backup script finished."
How it works: This script automates the process of creating timestamped backups of a specified directory. It compresses the directory into a gzipped tar archive and stores it in a designated backup location. Additionally, it implements a retention policy, automatically deleting backups older than a configurable number of days, helping to manage disk space. This is essential for disaster recovery and maintaining system integrity for web projects.

Need help integrating this into your project?

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

Hire DigitalCodeLabs