BASH

Create a Timestamped Directory Backup

Learn how to easily create timestamped tar.gz backups of important directories using a simple bash script, perfect for data preservation and automation.

#!/bin/bash

# Configuration
SOURCE_DIR="/path/to/your/source" # Directory to backup
BACKUP_ROOT_DIR="/path/to/your/backups" # Where backups will be stored
RETENTION_DAYS=7 # How many days to keep old backups

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

# Generate timestamp for the backup file name
DATE_SUFFIX=$(date +"%Y%m%d_%H%M%S")
BACKUP_FILE="${BACKUP_ROOT_DIR}/backup_$(basename "$SOURCE_DIR")_${DATE_SUFFIX}.tar.gz"

echo "Starting backup of $SOURCE_DIR to $BACKUP_FILE..."

# Create the gzipped tar archive
tar -czf "$BACKUP_FILE" -C "$(dirname "$SOURCE_DIR")" "$(basename "$SOURCE_DIR")"

if [ $? -eq 0 ]; then
  echo "Backup created successfully."
else
  echo "ERROR: Backup failed!"
  exit 1
fi

# Optional: Remove old backups
if [ -n "$RETENTION_DAYS" ] && [ "$RETENTION_DAYS" -gt 0 ]; then
  echo "Removing backups older than $RETENTION_DAYS days..."
  find "$BACKUP_ROOT_DIR" -type f -name "backup_$(basename "$SOURCE_DIR")_*.tar.gz" -mtime +$RETENTION_DAYS -delete
  echo "Old backups cleaned up."
fi
How it works: This script automates the creation of a compressed tarball backup for a specified directory. It generates a unique, timestamped filename for each backup, ensuring that previous backups are not overwritten. The script also includes an optional feature to automatically clean up old backups based on a configurable retention period, helping manage disk space efficiently. It's ideal for scheduled tasks like daily website or database backups.

Need help integrating this into your project?

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

Hire DigitalCodeLabs