← Back to all snippets
BASH

Automating Timestamped Directory Backups

Learn how to create an automated bash script to back up a specified directory with a unique timestamp, ideal for web project deployments or configuration management.

#!/bin/bash

# Configuration
SOURCE_DIR="/var/www/mywebapp"
BACKUP_DIR="/opt/backups/mywebapp"
DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_FILE="${BACKUP_DIR}/webapp_backup_${DATE}.tar.gz"
LOG_FILE="${BACKUP_DIR}/backup.log"

mkdir -p "${BACKUP_DIR}"

echo "[$(date +'%Y-%m-%d %H:%M:%S')] Starting backup of ${SOURCE_DIR} to ${BACKUP_FILE}" >> "${LOG_FILE}"

tar -czf "${BACKUP_FILE}" -C "$(dirname ${SOURCE_DIR})" "$(basename ${SOURCE_DIR})" >> "${LOG_FILE}" 2>&1

if [ $? -eq 0 ]; then
  echo "[$(date +'%Y-%m-%d %H:%M:%S')] Backup successful: ${BACKUP_FILE}" >> "${LOG_FILE}"
else
  echo "[$(date +'%Y-%m-%d %H:%M:%S')] Backup failed for ${SOURCE_DIR}" >> "${LOG_FILE}"
  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 "[$(date +'%Y-%m-%d %H:%M:%S')] Old backups cleaned up." >> "${LOG_FILE}"
How it works: This bash script automates the process of creating timestamped backups of a specified directory. It uses `tar` to compress the source directory into a `.tar.gz` archive, appending the current date and time to the filename for uniqueness. The script also creates the backup directory if it doesn't exist, logs its operations to a file, and includes an optional step to clean up old backups, keeping the disk space manageable. This is invaluable for maintaining snapshots of web application code or data.

Need help integrating this into your project?

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

Hire DigitalCodeLabs