BASH

Create Timestamped Backups of Directories

A Bash script to automatically create compressed, timestamped backups of a specified directory, essential for data recovery and versioning.

#!/bin/bash

SOURCE_DIR="/var/www/html/my-app"
BACKUP_DIR="/backups/my-app"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
BACKUP_FILE="${BACKUP_DIR}/my-app-backup-${TIMESTAMP}.tar.gz"

mkdir -p "$BACKUP_DIR"

if tar -czf "$BACKUP_FILE" "$SOURCE_DIR"; then
  echo "$(date): Backup of $SOURCE_DIR created successfully at $BACKUP_FILE"
  # Optional: Remove old backups (e.g., keep last 7 days)
  # find "$BACKUP_DIR" -type f -name "my-app-backup-*.tar.gz" -mtime +7 -delete
else
  echo "$(date): Error creating backup of $SOURCE_DIR"
  exit 1
fi
How it works: This script automates the process of creating compressed backups. It defines a source directory and a backup destination. It generates a unique timestamp for the backup filename and then uses `tar` to compress the source directory into a `.tar.gz` archive in the specified backup location. Error handling is included.

Need help integrating this into your project?

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

Hire DigitalCodeLabs