I have a script which creates folders in a backup folder by the current date. This script is run once a day, every day via cron.
Is there a way to remove the folders older than 3 days via folder name? something like
date -3 ?
Script that works: Thank you to Jo So. This script creates a folder by date. Compresses the files for backup, sticks them in your backup directory and clears out backups older than 3 days 🙂
#!/bin/bash
cd /home/backups
mkdir $(date +%Y-%m-%d)
cd /opt/
tar -pczf /home/backups/$(date +%Y-%m-%d)/opt.tar.gz code
cd /var/
tar -pczf /home/backups/$(date +%Y-%m-%d)/var.tar.gz work
cd /home/backups/
threedaysago=`date -d "3 days ago" +%Y%m%d`
for backup in [0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]
do
backupdate=`echo "$backup" | tr -d -` # remove dashes
if test "$backupdate" -lt "$threedaysago"
then
rm -rf "$backup"
fi
done
Work independently of mtime, and I can tell you that it will not break under particularly strange corner cases 😉