BASH
Automate Daily Directory Backups with Timestamp
Learn to create a bash script for daily automated backups of critical web project directories, saving them with timestamps for easy recovery and versioning.
#!/bin/bash
BACKUP_DIR="/var/www/mywebsite"
DEST_DIR="/backups/mywebsite_daily"
TIMESTAMP=$(date +"%Y%m%d%H%M%S")
ARCHIVE_NAME="website_backup_$TIMESTAMP.tar.gz"
RETENTION_DAYS=7
# Create destination directory if it doesn't exist
mkdir -p "$DEST_DIR"
# Create the archive
tar -czf "$DEST_DIR/$ARCHIVE_NAME" -C "$(dirname "$BACKUP_DIR")" "$(basename "$BACKUP_DIR")"
# Remove old backups
find "$DEST_DIR" -type f -name "website_backup_*.tar.gz" -mtime +$RETENTION_DAYS -delete
if [ $? -eq 0 ]; then
echo "Backup of $BACKUP_DIR completed successfully to $DEST_DIR/$ARCHIVE_NAME"
echo "Old backups older than $RETENTION_DAYS days removed."
else
echo "Backup failed!" >&2
exit 1
fi
How it works: This script automates daily backups of a specified directory. It creates a compressed tarball with a timestamp, stores it in a designated backup location, and automatically cleans up backups older than a configurable number of days, ensuring efficient disk space usage.