I have written the script that rotates all of the backups within one folder, keeping X daily, Y weekly and Z monthly backups.
I take all of the backups to folders
/root/backup/YYYYMMDD
on daily basis.
Then, i have the following rotating script:
#!/bin/bash
echo > /root/keep.txt
#writing dates of the backups that should be kept to the array
for i in {0..7}; do ((keep[$(date +%Y%m%d -d "-$i day")]++)); done
for i in {0..4}; do ((keep[$(date +%Y%m%d -d "sunday-$((i+1)) week")]++)); done
for i in {0..12}; do
DW=$(($(date +%-W)-$(date -d $(date -d "$(date +%Y-%m-15) -$i month" +%Y-%m-01) +%-W)))
for (( AY=$(date -d "$(date +%Y-%m-15) -$i month" +%Y); AY < $(date +%Y); AY++ )); do
((DW+=$(date -d $AY-12-31 +%W)))
done
((keep[$(date +%Y%m%d -d "sunday-$DW weeks")]++))
done
for i in {0..5}; do
DW=$(date +%-W)
for (( AY=$(($(date +%Y)-i)); AY < $(date +%Y); AY++ )); do
((DW+=$(date -d $AY-12-31 +%W)))
done
((keep[$(date +%Y%m%d -d "sunday-$DW weeks")]++))
done
#writing the array to file keep.txt line by line
for i in ${!keep[@]}; do echo $i >> /root/keep.txt; done
#delete all files that not mentioned in keep.txt
cd /root/backup
ls -1 /root/backup/ | sort /root/keep.txt /root/keep.txt - | uniq -u | xargs rm -rf
rm /root/keep.txt
This will keep 7 daily, 4 weekly, 12 monthly and 5 yearly backups.
I have got the most part of the logic from this topic