Skip to content

Instantly share code, notes, and snippets.

@HEPOSHEIKKI
Last active March 23, 2024 10:19
Show Gist options
  • Save HEPOSHEIKKI/68f565ca524d72eefeafc786156b7147 to your computer and use it in GitHub Desktop.
Save HEPOSHEIKKI/68f565ca524d72eefeafc786156b7147 to your computer and use it in GitHub Desktop.
Bash script for keeping X number of zip files, deleting the oldest one when limit is exceeded
#!/bin/bash
# Directory containing the zip files
backup_dir="/path/to/backups"
log_file="/var/log/purge-backups.log"
# Maximum number of zip files to keep
max_files=30
cd "$backup_dir" || exit
# Create log file
if [ ! -e "$log_file" ]; then
if ! touch "$log_file" > /dev/null 2>&1; then
echo "[FATAL] Failed to create log file" | ts
exit 1
fi
fi
# Trim the file to only contain 100 + last session lines of logs
log_content=$(tail -n 100 $log_file)
echo "$log_content" > $log_file
unset $log_content
echo "[SESSION]" | ts | tee -a $log_file
# Count the number of zip files
num_files=$(ls -1 *.zip 2>/dev/null | wc -l)
# If there are more than max_files, delete the oldest ones
if [ "$num_files" -ge "$max_files" ]; then
expired=$(ls -1t *.zip | tail -n +"$((max_files + 1))")
if [ -z "$expired" ];
then echo "[INFO] No files to remove" | ts | tee -a $log_file
exit 0
fi
while IFS= read -r file; do
echo "[INFO] Removing file: $file" | ts | tee -a $log_file
if ! rm -f "$file"; then
echo "[WARN] Failed to remove file: $file" | ts | tee -a $log_file
fi
done <<< "$expired"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment