BASH
Automating Daily Directory Backups with Timestamping
Learn to create a robust Bash script for daily directory backups, including timestamping archives and automatically cleaning up old backups to save disk space.
#!/bin/bash
BACKUP_DIR="/path/to/backups"
SOURCE_DIR="/path/to/your/web_project"
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
ARCHIVE_NAME="web_project_backup_${TIMESTAMP}.tar.gz"
RETENTION_DAYS=7 # Keep backups for 7 days
mkdir -p "$BACKUP_DIR"
echo "Starting backup of $SOURCE_DIR to $BACKUP_DIR/$ARCHIVE_NAME..."
tar -czf "$BACKUP_DIR/$ARCHIVE_NAME" -C "$(dirname "$SOURCE_DIR")" "$(basename "$SOURCE_DIR")"
if [ $? -eq 0 ]; then
echo "Backup completed successfully."
echo "Cleaning up old backups (older than $RETENTION_DAYS days)..."
find "$BACKUP_DIR" -type f -name "web_project_backup_*.tar.gz" -mtime +$RETENTION_DAYS -delete
echo "Cleanup complete."
else
echo "Backup failed!"
exit 1
fi
How it works: This script automates the backup of a specified directory. It creates a gzipped tar archive with a timestamp, stores it in a designated backup directory, and then removes any backups older than a configurable number of days, helping manage disk space.