BASH
Automate Directory Backup with Timestamp
Learn to create a robust Bash script for automating directory backups, appending a timestamp to each archive for easy versioning and recovery.
#!/bin/bash
# Define source directory and backup directory
SOURCE_DIR="/var/www/html"
BACKUP_DIR="/backups/web"
# 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)
# Define backup filename
BACKUP_FILE="$BACKUP_DIR/web_backup_$TIMESTAMP.tar.gz"
# Create the tarball backup
tar -czf "$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!"
fi
How it works: This script creates a compressed archive (tar.gz) of a specified source directory. It uses `date` to generate a unique timestamp, ensuring each backup file has a distinct name for easy identification and versioning. The `mkdir -p` command ensures the backup directory exists before the operation, and error handling checks the `tar` command's exit status. This is ideal for automated daily or weekly backups.