BASH

Automated Directory Backup with Timestamp and Compression

Learn to create a robust bash script for automated directory backups, compressing them into a timestamped tarball for easy recovery and versioning on web servers.

#!/bin/bash

# Configuration
SOURCE_DIR="/var/www/mywebsite"
BACKUP_DIR="/var/backups/mywebsite"
DATE=$(date +%Y-%m-%d_%H-%M-%S)
BACKUP_FILENAME="website_backup_$DATE.tar.gz"
LOG_FILE="/var/log/mywebsite_backup.log"

mkdir -p "$BACKUP_DIR" || { echo "Failed to create backup directory." >> "$LOG_FILE"; exit 1; }

echo "Starting backup of $SOURCE_DIR to $BACKUP_DIR/$BACKUP_FILENAME at $DATE" >> "$LOG_FILE"

tar -czf "$BACKUP_DIR/$BACKUP_FILENAME" -C "$(dirname "$SOURCE_DIR")" "$(basename "$SOURCE_DIR")" 2>> "$LOG_FILE"

if [ $? -eq 0 ]; then
  echo "Backup completed successfully." >> "$LOG_FILE"
  # Optional: Delete backups older than N days
  find "$BACKUP_DIR" -type f -name "*.tar.gz" -mtime +7 -delete 2>> "$LOG_FILE"
  echo "Old backups cleaned up." >> "$LOG_FILE"
else
  echo "Backup failed!" >> "$LOG_FILE"
  exit 1
fi
How it works: This script automates the process of backing up a specified directory, compressing it into a timestamped tarball, and optionally cleaning up old backups. It's ideal for regularly backing up website files or application code, ensuring a point-in-time recovery option. Error messages are logged for easy debugging and scheduled execution via cron.

Need help integrating this into your project?

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

Hire DigitalCodeLabs