BASH

Create Timestamped Compressed Backups

Automate creation of timestamped, compressed backups of directories or project files, ensuring data integrity and easy recovery for web projects.

#!/bin/bash

# Configuration
SOURCE_DIR="/var/www/mywebapp"
BACKUP_DIR="/backups/mywebapp"
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
BACKUP_NAME="webapp_backup_$TIMESTAMP.tar.gz"

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

echo "Starting backup of $SOURCE_DIR to $BACKUP_DIR/$BACKUP_NAME"

# Create the compressed tar archive
tar -czf "$BACKUP_DIR/$BACKUP_NAME" -C "$(dirname "$SOURCE_DIR")" "$(basename "$SOURCE_DIR")"

# Check if tar command was successful
if [ $? -eq 0 ]; then
  echo "Backup successful: $BACKUP_DIR/$BACKUP_NAME"
else
  echo "Backup failed!"
  exit 1
fi

# Optional: Clean up old backups (e.g., keep last 7 days)
# find "$BACKUP_DIR" -type f -name "webapp_backup_*.tar.gz" -mtime +7 -delete
# echo "Old backups cleaned up."
How it works: This script automates the creation of compressed, timestamped backups for a specified directory. It uses the 'tar' utility with the '-c' (create), '-z' (gzip compression), and '-f' (filename) flags to generate a '.tar.gz' archive. The timestamp ensures unique backup names, and the script includes error checking. An optional commented-out line demonstrates how to prune old backups, providing a useful retention policy.

Need help integrating this into your project?

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

Hire DigitalCodeLabs