Bash script to remove data older than a specific date

0

Bash script to remove files/folders older than a specific data specified in file/folder name.

Here an example for Nextcloud backups stored in /backup folder.

#!/bin/bash

echo "Calculate date 7 days ago"
keepdays=$(date "+%Y%m%d" -d "7 days ago")
echo Backups older than $keepdays will be removed!
echo ""

echo "Cleanup nextcloud backups"
for backup in /backup/nextcloud/*
do
        backupdate=`echo "$backup" | grep -oP '\d{8}'`

        if test "$backupdate" -lt "$keepdays"
        then
                echo "Removing $backup..."
                rm -R $backup #add v option for verbose output
                echo "$backup removed successfully!"
                echo ""
        fi
done
echo "nextcloud backups cleaned up"


Another example for GitLab backups stored in /backup folder.

#!/bin/bash

echo "Calculate date 7 days ago"
keepdays=$(date "+%Y%m%d" -d "7 days ago")

echo "Cleanup gitlab backups"
for backup in /backup/gitlab/*
do
        backupdate=`echo "$backup" | grep -oP '\d{10}'`
        if test "$backupdate" != ""
        then
                backupdate=`date "+%Y%m%d" -d @$backupdate`
                if test "$backupdate" -lt "$keepdays"
                then
                        echo "Removing $backup..."
                        rm -R $backup #add v option for verbose output
                        echo "$backup removed successfully!"
                        echo ""
                fi
        fi
done
echo "gitlab backups cleaned up"
Share.

About Author

Christian Unnerstall

Christian Unnerstall, founder of devshooin.com, enjoys designing and building things that look nice and work well, whether it's websites or services within the interwebs. Have questions - feel free to reach out to him. Enjoy

Leave a Reply