← Back to all snippets
BASH

Automating File and Directory Backups

Create a simple Bash script to automate daily backups of specified files or directories, compressing them and adding a timestamp for easy recovery.

#!/bin/bash
SOURCE_DIR="/var/www/html/mywebapp"
BACKUP_DIR="/mnt/backups/mywebapp"
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
BACKUP_FILE="$BACKUP_DIR/webapp_backup_$TIMESTAMP.tar.gz"

mkdir -p "$BACKUP_DIR"

echo "Starting backup of $SOURCE_DIR to $BACKUP_FILE..."
tar -czf "$BACKUP_FILE" "$SOURCE_DIR"

if [ $? -eq 0 ]; then
    echo "Backup successful: $BACKUP_FILE"
    # Optional: Remove old backups (e.g., older than 7 days)
    find "$BACKUP_DIR" -type f -name 'webapp_backup_*.tar.gz' -mtime +7 -delete
    echo "Old backups cleaned up."
else
    echo "Error: Backup failed."
    exit 1
fi
How it works: This script automates creating compressed tarball backups of a specified source directory. It creates a timestamped archive, stores it in a designated backup directory, and optionally cleans up backups older than 7 days, providing essential data protection for web applications or configuration files.

Need help integrating this into your project?

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

Hire DigitalCodeLabs