BASH
Automated Directory Backup with Timestamp
Create a robust Bash script to automatically backup a specified directory, compressing it into a timestamped archive for easy versioning and recovery.
#!/bin/bash
SOURCE_DIR="/var/www/mywebapp" # Directory to backup
BACKUP_DIR="/home/user/backups" # Destination for backups
DATE=$(date +"%Y%m%d_%H%M%S")
ARCHIVE_NAME="webapp_backup_${DATE}.tar.gz"
FULL_PATH="${BACKUP_DIR}/${ARCHIVE_NAME}"
# Create backup directory if it doesn't exist
mkdir -p "${BACKUP_DIR}"
echo "Starting backup of ${SOURCE_DIR}..."
tar -czf "${FULL_PATH}" -C "$(dirname "${SOURCE_DIR}")" "$(basename "${SOURCE_DIR}")"
if [ $? -eq 0 ]; then
echo "Backup successful: ${FULL_PATH}"
# 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 "Old backups cleaned up."
else
echo "Backup failed!"
exit 1
fi
How it works: This script automates creating a compressed backup of a specified directory. It uses `date` to generate a unique timestamp for the archive name, ensuring multiple backups can coexist. `mkdir -p` safely creates the backup destination. `tar -czf` compresses the source directory, and error checking `if [ $? -eq 0 ]` verifies success. An optional `find` command is commented out for managing old backups.