#!/usr/bin/perl # # Script for cleaning up backup dir used by backup-run.sh # # Author: Alan Briolat # # Include stuff that is needed #use Getopt::Std; # Set base backup dir #$root_dir = "/backup/foo"; if($ARGV[0] =~ /(\/.+\/[^\/]+)(|\/)$/) { $root_dir = $1; } else { print "Usage: backup-clean.pl directory [ filecount ]\n"; exit; } # Number of recent backups to keep (1 = only latest) $archive = 1; if($ARGV[1] =~ /[0-9]+/) { $archive = $ARGV[1]; } # Open the directory, otherwise kill the script opendir(DIR, $root_dir) || die "Could not open $root_dir: $!"; # List all of the files in an array and sort in ascending order (newest last) @filelist = grep { !/^\./ } readdir(DIR); @filelist = sort(@filelist); # Iterate through the file list my @files; foreach (@filelist) { # Backup filename $file = $_; # Grab parts of the filename /([\w]+)-(.*?)-([\d]{4})-([\d]{2})-([\d]{2})-([\d]{2})([\d]{2})\.tar\.bz2/; # Create hash key $key = "$1-$2"; # If array doesnt exist create it if(not ref($files{$key}) eq "ARRAY") { @{ $files{$key} } = (); } # Push the file onto the array push(@{ $files{$key} }, $file); #print "Added $6:$7 $3-$4-$5 to $1-$2\n"; } foreach(keys(%files)) { #print "$_\n"; # Pop the defined number of files off the list # (ones left on the list get deleted) for($i = 0; $i < $archive; $i++) { pop(@{$files{$_}}); } # Delete files that are left foreach(@{$files{$_}}) { #print "\t$_\n"; system(("rm", "$root_dir/$_")); } }