Skip to content

Instantly share code, notes, and snippets.

@dansimau
Created January 20, 2012 09:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dansimau/1646504 to your computer and use it in GitHub Desktop.
Save dansimau/1646504 to your computer and use it in GitHub Desktop.
Prunes Squiz CMS backups to the last X number of days. Will bail out if the backups have broken, to avoid deleting backups if they may be needed.
#!/bin/bash
#
# Reduces the total number of Squiz CMS backups to the last X days', whilst
# also ensuring at least X number of backups always exist.
#
# In other words, we want only the last X number of days' backups unless the
# backups have failed, in which case we'd prefer to keep the old ones until
# the backup is running again.
#
# dsimmons@squiz.co.uk
# 2012-01-20
#
filemask="???_????-??-??_??-??.tar.gz"
if [ $# -lt 2 ]; then
echo "Reduces Squiz CMS backup files to the last X days'" >&2
echo "Usage: $0 <path to backups> <number of last days' backups to keep> [-f]" >&2
echo " (-f means: actually do something - otherwise, just a dry-run)" >&2
exit 99
fi
dir=$1
x=$2
[ "$3" != "-f" ] && dryrun=1
# Count total number of backup files
n=$(find "$dir" -mindepth 1 -maxdepth 1 -type f -name "$filemask" -print |wc -l)
[ $dryrun ] && echo "$n backups in total"
# Count number of backup files to be deleted
c=$(find "$dir" -mindepth 1 -maxdepth 1 -type f -name "$filemask" -daystart -mtime +$((x-1)) |wc -l)
if [ $c -eq 0 ]; then
echo "No backups to delete."
exit
elif [ $dryrun ]; then
echo "$c to delete:"
find "$dir" -mindepth 1 -maxdepth 1 -type f -name "$filemask" -daystart -mtime +$((x-1))
echo "(Use -f to actually delete them)"
exit
fi
# If the total number of backups *AFTER* deletion is less than the number of
# last days' backups we want to keep, then don't delete anything
if [ ! $(($n-$c)) -lt $x ]; then
# Delete the backups
find "$dir" -mindepth 1 -maxdepth 1 -type f -name "$filemask" -daystart -mtime +$((x-1)) -delete
else
echo "WARNING: Skipping removal of backups as it would result in total number of backups less than. $x" >&2
echo "HINT: Did your backup run yesterday?" >&2
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment