Skip to content

Instantly share code, notes, and snippets.

@calebjones
Last active December 12, 2017 17:50
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 calebjones/678cfbb7f28a7a4714b4 to your computer and use it in GitHub Desktop.
Save calebjones/678cfbb7f28a7a4714b4 to your computer and use it in GitHub Desktop.
Linux script to rotate backup files (keeps past 7 days then switches to weekly for the past 30 days then keeps only monthly files)
#!/bin/bash
# backup location with daily files
# format: .*_[DATE]_.*
# date format: YYYY-MM-DD
backupLocation="/path/to/backups"
if [ -z "$backupLocation" ]; then
echo 'Must set $backupLocation'
exit 1
fi
# delete non Sunday and non "first day of the month" files older than a week
find $backupLocation -mtime +7 | while read fname; do
fileDate=`echo $fname | awk -F"_" '{print $2}'`
fileDow=`date --date="${fileDate}" "+%a"`
fileDom=`echo $fname | awk -F"_" '{print $2}' | awk -F"-" '{print $3}'`
#echo "${fname} - ${fileDow} - ${fileDom}"
if [ "${fileDow}" != "Sun" ] && [ "${fileDom}" != "01" ] && [ -f ${fname} ]; then
#echo "rm ${fname} (${fileDow} - ${fileDom})"
rm ${fname}
fi
done
# delete non first day of month files older than a month (clear out weekly files)
find $backupLocation -mtime +30 | while read fname; do
fileDom=`echo $fname | awk -F"_" '{print $2}' | awk -F"-" '{print $3}'`
#echo "${fname} - ${fileDom}"
if [ "${fileDom}" != "01" ] && [ -f ${fname} ]; then
#echo "rm ${fname} (${fileDom})"
rm ${fname}
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment