BASH

Backup Critical Configuration Files

Create timestamped tar.gz backups of important configuration files or directories, ensuring you have a restore point before making system-level changes.

#!/bin/bash

# Directories/files to backup
TARGETS=(
  "/etc/nginx"
  "/etc/apache2"
  "/etc/php"
  "/etc/hosts"
  "~/.ssh"
  "/etc/mysql"
)

# Backup destination (create this directory if it doesn't exist)
BACKUP_DIR="/var/backups/configs"

# Create backup directory if it doesn't exist
mkdir -p "$BACKUP_DIR" || { echo "Error: Could not create backup directory $BACKUP_DIR"; exit 1; }

TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
BACKUP_FILENAME="config_backup_${TIMESTAMP}.tar.gz"

echo "Starting backup of critical configuration files..."

# Create a temporary list of existing targets to backup
EXISTING_TARGETS=()
for target in "${TARGETS[@]}"; do
  expanded_target=$(eval echo "$target") # Expand ~ to home directory
  if [ -e "$expanded_target" ]; then
    EXISTING_TARGETS+=("$expanded_target")
  else
    echo "Warning: Target '$expanded_target' not found, skipping."
  fi
done

if [ ${#EXISTING_TARGETS[@]} -eq 0 ]; then
  echo "No existing targets to backup. Exiting."
  exit 1
fi

# Create the tar.gz archive
# Using -C / ensures paths are absolute from root within the archive
tar -czf "$BACKUP_DIR/$BACKUP_FILENAME" -C / "${EXISTING_TARGETS[@]%/}"

if [ $? -eq 0 ]; then
  echo "Backup successful! Archive saved to: $BACKUP_DIR/$BACKUP_FILENAME"
  echo "Size: $(du -h "$BACKUP_DIR/$BACKUP_FILENAME" | awk '{print $1}')"
else
  echo "Backup failed!"
fi

# Optional: Clean up old backups (e.g., keep last 7 days)
# echo "Cleaning up old backups (keeping last 7 days)..."
# find "$BACKUP_DIR" -type f -name "config_backup_*.tar.gz" -mtime +7 -delete
# echo "Old backups cleaned up."
How it works: This script automates the backup of critical configuration files and directories, such as Nginx, Apache, PHP configurations, SSH settings, and MySQL configs. It creates a timestamped `tar.gz` archive in a specified backup directory, ensuring that web developers have a recoverable state before making potentially breaking changes to their server configurations. It includes error handling for non-existent targets and confirms the backup's success.

Need help integrating this into your project?

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

Hire DigitalCodeLabs