Bash script to delete old files leaving last few

I was in need of a way to delete the oldest number of backup files, but leaving the last few. Most searches online that I found were dependent on the find –exec samples, which I didn’t want to use, well, because my idea was that if I was to use the –mtime flag for find, and the backups failed to run for say the last 7 days, it would nuke all my backups while I was on vacation. I wanted to keep the last 3 (for example), regardless of modified time.

here it is:

#!/bin/bash# edit above line to the path to bash#command to find is: "which bash"###############set your variables below############ prefix is the prefix of the filename,# example filename: server1-07-20-2011.bak, the prefix would be: server1# numtokeep is the number of backups you would like to preserve# backupFolder is the location of your backup files, exclude trailing slash#prefix=poopnumtokeep=3backupFolder=/home/dustin/test################################################### go to backup folder just to be safecd $backupFolder## count how many files are in backup folder, and set to a variablefilecount=`ls -l $backupFolder/$prefix* | wc -l`## checking to see if number of backups is greater than number to keepif [ $filecount -gt $numtokeep ] then extras=$(($filecount - $numtokeep)) echo "leaving $numtokeep, deleting $extras" for counter in $(ls -ltr $backupFolder/$prefix* | head -n $extras | awk '{ print $8 }') do if [ "$1" == "--test" ] then echo "Will delete: $counter" else echo "deleting: $counter" rm -R $counter if [ $? != 0 ] ; then echo "Error deleting: $counter" else echo "Successfully deleted: $counter" fi fi done else echo "not enough backups to delete"fi

In order to use, you will need to copy and paste that into a file on your linux box using your favorite editor. you will need to chmod +x /path/to/fileName, and most importantly edit the three variables on top to suit your needs.

You can run as test out to see what it is going to delete by executing it with a “ –-test ” argument:

any other argument is ignored, and will start deleting, so be careful.

you can battle my logic for the need for this all you want… I *do* have a use for it (such as make disk space available before a backup is run), so piss off if you’re going to comment with something negative.