BASH
Backup a Directory to a Timestamped Tar Archive
Automate creating local, timestamped `.tar` archives of important directories. Essential for quick backups of web application files, configuration, or user uploads.
#!/bin/bash
SOURCE_DIR="/var/www/mywebapp" # Directory to backup
BACKUP_DIR="/mnt/backups/webapp_data" # Destination for backups
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
BACKUP_FILENAME="webapp_backup_$TIMESTAMP.tar"
# Create backup directory if it doesn't exist
mkdir -p "$BACKUP_DIR"
echo "Starting backup of $SOURCE_DIR to $BACKUP_DIR/$BACKUP_FILENAME..."
tar -cvf "$BACKUP_DIR/$BACKUP_FILENAME" -C "$(dirname "$SOURCE_DIR")" "$(basename "$SOURCE_DIR")"
if [ $? -eq 0 ]; then
echo "Backup successful: $BACKUP_DIR/$BACKUP_FILENAME"
echo "Size: $(du -sh "$BACKUP_DIR/$BACKUP_FILENAME" | awk '{print $1}')"
else
echo "Backup failed!"
exit 1
fi
How it works: This script creates a timestamped `.tar` archive of a specified source directory. It's useful for taking snapshots of web application codebases, configuration files, or user-uploaded content. The script first ensures the backup destination exists, then uses `tar -cvf` to create the archive, preserving directory structure. It also includes basic error checking and reports the backup size.