#!/bin/bash
# Backup Script with Error Handling
set -e # Exit on error
set -u # Exit on undefined variable
# Variables
BACKUP_DIR="/backup"
SOURCE_DIR="/var/www"
DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_FILE="backup_${DATE}.tar.gz"
# Functions
function log_message() {
echo "[$(date +'%Y-%m-%d %H:%M:%S')] $1"
}
function create_backup() {
local source=$1
local dest=$2
log_message "Starting backup of ${source}"
if [ -d "${source}" ]; then
tar -czf "${dest}" "${source}" 2>&1 | tee -a backup.log
if [ ${PIPESTATUS[0]} -eq 0 ]; then
log_message "Backup completed successfully"
return 0
else
log_message "Backup failed!"
return 1
fi
else
log_message "Error: Source directory not found"
return 1
fi
}
# Main script
if [ ! -d "${BACKUP_DIR}" ]; then
mkdir -p "${BACKUP_DIR}"
fi
# Check available space
available_space=$(df -BG "${BACKUP_DIR}" | awk 'NR==2 {print $4}' | sed 's/G//')
if [ "${available_space}" -lt 10 ]; then
log_message "Warning: Less than 10GB available"
fi
# Create backup
create_backup "${SOURCE_DIR}" "${BACKUP_DIR}/${BACKUP_FILE}"
# Cleanup old backups (keep last 7 days)
find "${BACKUP_DIR}" -name "backup_*.tar.gz" -mtime +7 -delete
log_message "Backup process completed"