BASH

Automate File Backup with Timestamp and Compression

Create a robust Bash script to automatically backup specified files or directories, adding a timestamp to the archive name and compressing it using `tar` and `gzip` for storage.

#!/bin/bash

# Configuration
BACKUP_SOURCE="/path/to/your/important_data" # Change this to the directory/file you want to backup
BACKUP_DEST="/path/to/your/backups"       # Change this to your backup destination
FILENAME_PREFIX="my_app_backup"

# Create backup destination if it doesn't exist
mkdir -p "$BACKUP_DEST"

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

# Define backup filename
BACKUP_FILENAME="${FILENAME_PREFIX}_${TIMESTAMP}.tar.gz"

# Perform the backup using tar with gzip compression
echo "Starting backup of '$BACKUP_SOURCE' to '$BACKUP_DEST/$BACKUP_FILENAME'..."
tar -czf "$BACKUP_DEST/$BACKUP_FILENAME" -C "$(dirname "$BACKUP_SOURCE")" "$(basename "$BACKUP_SOURCE")"

# Check if backup was successful
if [ $? -eq 0 ]; then
  echo "Backup successful: $BACKUP_DEST/$BACKUP_FILENAME"
else
  echo "Backup failed!" >&2
  exit 1
fi

# Optional: Clean up old backups (e.g., keep last 7 days)
# echo "Cleaning up old backups (older than 7 days)..."
# find "$BACKUP_DEST" -type f -name "${FILENAME_PREFIX}_*.tar.gz" -mtime +7 -delete
# echo "Old backups cleaned up."
How it works: This script automates the backup process for a specified directory or file. It configures source and destination paths, ensures the backup directory exists, and generates a timestamped filename for the archive. It then uses `tar -czf` to create a compressed `tar.gz` archive. The `-C "$(dirname "$BACKUP_SOURCE")" "$(basename "$BACKUP_SOURCE")"` ensures that the directory structure inside the tarball is clean, avoiding unnecessary parent directories. Finally, it checks the exit status of the `tar` command to report success or failure. An optional section for cleaning old backups (e.g., older than 7 days) is included but commented out.

Need help integrating this into your project?

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

Hire DigitalCodeLabs