#!/bin/bash # Configuration SOURCE_DIR="/var/www/mywebapp" # Directory to backup BACKUP_ROOT_DIR="/mnt/backups/webapps" # Root directory where backups will be stored RETENTION_COUNT=5 # Number of latest backups to keep # Derive backup directory specific to the source APP_NAME=$(basename "$SOURCE_DIR") BACKUP_DIR="$BACKUP_ROOT_DIR/$APP_NAME" TIMESTAMP=$(date +%Y%m%d_%H%M%S) BACKUP_FILENAME="${APP_NAME}_backup_$TIMESTAMP.tar.gz" FULL_BACKUP_PATH="$BACKUP_DIR/$BACKUP_FILENAME" # --- Pre-checks --- if [ ! -d "$SOURCE_DIR" ]; then echo "Error: Source directory '$SOURCE_DIR' does not exist." >&2 exit 1 fi # Create backup directory if it doesn't exist mkdir -p "$BACKUP_DIR" if [ $? -ne 0 ]; then echo "Error: Failed to create backup directory '$BACKUP_DIR'. Check permissions." >&2 exit 1 fi echo "Starting backup of '$SOURCE_DIR' to '$FULL_BACKUP_PATH'" # Create a gzipped tar archive of the source directory # -C: Change to directory before adding. This ensures the archive only contains 'mywebapp', not '/var/www/mywebapp' tar -czf "$FULL_BACKUP_PATH" -C "$(dirname "$SOURCE_DIR")" "$(basename "$SOURCE_DIR")" if [ $? -eq 0 ]; then echo "Backup of '$SOURCE_DIR' created successfully at '$FULL_BACKUP_PATH'" else echo "Error: Backup failed!" >&2 rm -f "$FULL_BACKUP_PATH" # Clean up failed backup file exit 1 fi # --- Optional: Enforce Retention Policy --- echo "Enforcing retention policy: keeping last $RETENTION_COUNT backups." # List files, sort by time (newest last), skip directories, take all but the last N, and delete # '2>/dev/null || true' handles cases where there are less than N files find "$BACKUP_DIR" -maxdepth 1 -name "${APP_NAME}_backup_*.tar.gz" -printf '%T@ %p ' | sort -n | cut -d' ' -f2- | head -n -"$RETENTION_COUNT" | xargs -r rm -v echo "Backup process finished."