#!/bin/bash # This script keeps only one backup file per month for 2023 # It will keep the first backup of each month (usually the 1st day at midnight) # and delete all other 2023 backups # Create a deletion plan file deletion_plan="backup_deletion_plan_$(date +%Y%m%d_%H%M%S).txt" echo "Backup Deletion Plan - Created $(date)" > "$deletion_plan" echo "----------------------------------------" >> "$deletion_plan" echo "The following 2023 backup files will be kept:" >> "$deletion_plan" # Create an associative array to track which files to keep declare -A keep_files # Find all 2023 backup files and identify one per month to keep for file in backup_2023_*.sql.gz; do # Extract month from filename (position 13-14 in the filename) month=${file:13:2} # If we haven't marked a file to keep for this month yet, keep this one if [[ -z ${keep_files[$month]} ]]; then keep_files[$month]=$file echo "Keeping $file as the representative backup for month $month" echo "KEEP: $file" >> "$deletion_plan" fi done # Add a section for files to be deleted echo "" >> "$deletion_plan" echo "The following 2023 backup files will be deleted:" >> "$deletion_plan" # Now identify all 2023 backup files for deletion (without deleting yet) delete_count=0 for file in backup_2023_*.sql.gz; do # Check if this file is in our keep list keep=0 for keep_file in "${keep_files[@]}"; do if [[ "$file" == "$keep_file" ]]; then keep=1 break fi done # If not in keep list, mark for deletion if [[ $keep -eq 0 ]]; then echo "Marking for deletion: $file" echo "DELETE: $file" >> "$deletion_plan" delete_count=$((delete_count+1)) fi done # Add summary to deletion plan echo "" >> "$deletion_plan" echo "----------------------------------------" >> "$deletion_plan" echo "Summary: Will keep ${#keep_files[@]} files and delete $delete_count files" >> "$deletion_plan" echo "To execute this plan, run: ./execute_deletion_plan.sh" >> "$deletion_plan" # Create the execution script cat > execute_deletion_plan.sh << 'EOF' #!/bin/bash # Check if deletion plan file is provided if [ $# -ne 1 ]; then echo "Usage: $0 " exit 1 fi plan_file="$1" # Check if the file exists if [ ! -f "$plan_file" ]; then echo "Error: Deletion plan file not found: $plan_file" exit 1 fi echo "Executing deletion plan from: $plan_file" echo "----------------------------------------" # Process the deletion plan while IFS= read -r line; do if [[ $line == DELETE:* ]]; then file="${line#DELETE: }" if [ -f "$file" ]; then echo "Deleting: $file" rm "$file" else echo "Warning: File not found: $file" fi fi done < "$plan_file" echo "----------------------------------------" echo "Deletion plan execution completed." EOF chmod +x execute_deletion_plan.sh echo "Deletion plan created: $deletion_plan" echo "Review the plan and then execute it with: ./execute_deletion_plan.sh $deletion_plan"