← Back to all snippets
BASH

Create Timestamped Backups of Files and Directories

Learn to create reliable timestamped backups of your important files and directories using Bash with `tar` and `gzip` for easy recovery.

#!/bin/bash

# Directory to backup
SOURCE_DIR="/var/www/html/myapp"

# Directory to store backups
BACKUP_DIR="/backups/myapp"

# Name for the backup file prefix
BACKUP_PREFIX="myapp_backup"

# Get current date and time for timestamp
TIMESTAMP=$(date +%Y%m%d_%H%M%S)

# Create backup directory if it doesn't exist
mkdir -p "$BACKUP_DIR"

# Define the backup filename
BACKUP_FILE="$BACKUP_DIR/$BACKUP_PREFIX-$TIMESTAMP.tar.gz"

echo "Starting backup of '$SOURCE_DIR' to '$BACKUP_FILE'...

# Create a compressed tar archive
tar -czf "$BACKUP_FILE" -C "$(dirname "$SOURCE_DIR")" "$(basename "$SOURCE_DIR")"

if [ $? -eq 0 ]; then
  echo "Backup successful: $BACKUP_FILE"
else
  echo "Backup failed!"
  exit 1
fi

# Optional: Remove old backups (e.g., older than 30 days)
# find "$BACKUP_DIR" -name "*.tar.gz" -mtime +30 -delete
How it works: This script creates a compressed `tar.gz` archive of a specified source directory, including a unique timestamp in the filename. It ensures the backup destination directory exists and then uses `tar -czf` for compression and archiving. It also includes error checking for the `tar` command and an optional commented-out line to clean up old backups, making it suitable for automated backup routines.

Need help integrating this into your project?

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

Hire DigitalCodeLabs