Bash script to delete date folders by folder name

I have a script that creates folders in a backup folder by the current date. This script runs once a day, every day through cron.

Is there a way to delete folders older than 3 days via the folder name? sort of

date -3?

Script that works: Thanks Jo So. This script creates a folder by date. Compresses files for backup, inserts them into the backup directory and deletes backups for more 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
+1
source share
2 answers
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 in especially strange cases :-)

+3
source

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

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

find :

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

All Articles