BASH

Create Timestamped Tar.gz Backup of a Directory

Learn how to create compressed, timestamped tar.gz archives of any directory, perfect for web application backups and versioning.

#!/bin/bash
BACKUP_DIR="/var/www/mywebapp"
DEST_DIR="/mnt/backups/mywebapp"
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
FILENAME="mywebapp_backup_${TIMESTAMP}.tar.gz"

mkdir -p "$DEST_DIR" || { echo "Error: Could not create backup destination directory."; exit 1; }

echo "Starting backup of $BACKUP_DIR to $DEST_DIR/$FILENAME..."
tar -czf "$DEST_DIR/$FILENAME" -C "$(dirname "$BACKUP_DIR")" "$(basename "$BACKUP_DIR")"
if [ $? -eq 0 ]; then
    echo "Backup completed successfully: $DEST_DIR/$FILENAME"
else
    echo "Backup failed!"
    exit 1
fi
How it works: This script creates a compressed `tar.gz` archive of a specified directory. It generates a timestamp for the filename, ensuring unique backups. It includes error checking for directory creation and the backup process itself, making it robust for automated web application backups. The `-C` option allows `tar` to change the directory before adding files, ensuring the archive contains the directory itself rather than its parent path.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs