rezizter
rezizter

Reputation: 5168

bash script to remove date folders by folder name

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

Upvotes: 1

Views: 2672

Answers (2)

Jo So
Jo So

Reputation: 26501

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 ;-)

Upvotes: 3

hovanessyan
hovanessyan

Reputation: 31433

Removes daily backups (of type "regular file") older than 3 days:

rm -f `find $YOUR_BACKUP_DIR -maxdepth 1 -type f -mtime +3`

From find man page:

   -mtime n
          File's data was last modified n*24 hours ago.  See the  comments
          for -atime to understand how rounding affects the interpretation
          of file modification times.

Upvotes: 0

Related Questions