#!/bin/bash # This script is designed to perform an annual backup of a source directory directly to a compressed `.tar.xz` archive for maximum compression. # It allows excluding specified files or directories from the archive during the backup process. # Additionally, it generates a SHA-256 checksum for each archive, saving it in a corresponding `.sha256` file for integrity verification. # Finally, it removes older archives and their checksum files exceeding a specified retention period (e.g., 5 years), ensuring backup rotation. # Usage: # To use this script, save it as "annual_backup_with_max_compression.sh" and make it executable with the command `chmod +x annual_backup_with_max_compression.sh`. # You can define exclusions either in the EXCLUDE_LIST array or in a file specified by EXCLUDE_FILE. # Automate the execution annually by adding this cron job: `0 0 1 1 * /path/to/script/annual_backup_with_max_compression.sh` # Variables SOURCE_DIR="/path/to/source_directory" # Source directory to back up ARCHIVE_DIR="/path/to/archive_directory" # Directory where tar.xz archives are stored ARCHIVE_NAME="backup-$(date +%Y).tar.xz" # Archive name with the year CHECKSUM_FILE="$ARCHIVE_NAME.sha256" # SHA-256 checksum file name (relative path) RETENTION_YEARS=5 # Number of years to retain archives RETENTION_DAYS=$((RETENTION_YEARS * 365)) # Retention period in days (5 years) # Exclusion settings EXCLUDE_LIST=() # Inline exclusion list, add patterns here (e.g., "*.tmp", "node_modules") EXCLUDE_FILE="" # File with additional exclude patterns, one per line (e.g., "/path/to/exclude_file.txt") # Build tar exclusion options TAR_EXCLUDE_OPTIONS=() for pattern in "${EXCLUDE_LIST[@]}"; do TAR_EXCLUDE_OPTIONS+=("--exclude=$pattern") done if [ -n "$EXCLUDE_FILE" ]; then TAR_EXCLUDE_OPTIONS+=("--exclude-from=$EXCLUDE_FILE") fi # 1. Create a tar.xz archive directly from the source directory with maximum compression, preserving file permissions tar -cJf "$ARCHIVE_DIR/$ARCHIVE_NAME" "${TAR_EXCLUDE_OPTIONS[@]}" -C "$SOURCE_DIR" . --preserve-permissions # 2. Change to the archive directory and generate a SHA-256 checksum with relative paths ( cd "$ARCHIVE_DIR" || exit sha256sum "$ARCHIVE_NAME" > "$CHECKSUM_FILE" ) # 3. Remove older archives and checksum files (older than 5 years) find "$ARCHIVE_DIR" -type f -name "backup-*.tar.xz" -mtime +$RETENTION_DAYS -exec rm {} \; find "$ARCHIVE_DIR" -type f -name "backup-*.tar.xz.sha256" -mtime +$RETENTION_DAYS -exec rm {} \; echo "Annual backup with maximum compression and checksum completed: $ARCHIVE_NAME"