BASH

Automate Timestamped Directory Backup

Create a compressed, timestamped archive of a specified directory, ideal for regular backups of web project files, databases, or configurations.

#!/bin/bash

backup_directory() {
    if [ -z "$1" ] || [ -z "$2" ]; then
        echo "Usage: backup_directory <source_dir> <backup_destination_dir>"
        return 1
    fi

    SOURCE_DIR="$1"
    BACKUP_DEST_DIR="$2"
    TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
    ARCHIVE_NAME="$(basename "$SOURCE_DIR")_backup_$TIMESTAMP.tar.gz"
    ARCHIVE_PATH="$BACKUP_DEST_DIR/$ARCHIVE_NAME"

    if [ ! -d "$SOURCE_DIR" ]; then
        echo "Error: Source directory '$SOURCE_DIR' not found."
        return 1
    fi

    mkdir -p "$BACKUP_DEST_DIR"

    echo "Creating backup of '$SOURCE_DIR' to '$ARCHIVE_PATH'..."
    tar -czf "$ARCHIVE_PATH" -C "$(dirname "$SOURCE_DIR")" "$(basename "$SOURCE_DIR")"

    if [ $? -eq 0 ]; then
        echo "Backup successful: $ARCHIVE_PATH"
    else
        echo "Backup failed!"
    fi
}

# To use:
# backup_directory /var/www/html/mywebapp /mnt/backups/webapps
How it works: This script automates the process of creating compressed backups of a directory. It takes a source directory and a backup destination as arguments. It then generates a unique filename by appending a timestamp to the original directory name, creates a gzipped tar archive of the source directory, and stores it in the specified destination. This is crucial for disaster recovery and versioning of web application code or critical data.

Need help integrating this into your project?

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

Hire DigitalCodeLabs