BASH
Automate Daily Backups with Timestamps
Learn to create a bash script for automating daily backups of a directory, incorporating timestamps for unique archives and using tar for compression.
#!/bin/bash
# Configuration
SOURCE_DIR="/path/to/your/important/data"
BACKUP_DIR="/path/to/your/backup/location"
FILENAME="data_backup"
# Create backup directory if it doesn't exist
mkdir -p "$BACKUP_DIR"
# Get current date and time for filename
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
BACKUP_FILE="${BACKUP_DIR}/${FILENAME}_${TIMESTAMP}.tar.gz"
# Create the gzipped tar archive
tar -czvf "$BACKUP_FILE" "$SOURCE_DIR"
# Check if backup was successful
if [ $? -eq 0 ]; then
echo "Backup of $SOURCE_DIR successful: $BACKUP_FILE"
else
echo "Error: Backup of $SOURCE_DIR failed."
exit 1
fi
# Optional: Remove old backups (e.g., older than 7 days)
# find "$BACKUP_DIR" -name "${FILENAME}_*.tar.gz" -type f -mtime +7 -delete
exit 0
How it works: This script automates the process of backing up a specified directory. It generates a unique filename using the current date and time, then uses `tar` to create a gzipped archive of the source directory. It includes error checking to report success or failure and an optional line to prune old backups, making it suitable for cron jobs.