Advertisement
mikelieman

bin/clean_old_files.pl

Sep 2nd, 2013
310
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 2.06 KB | None | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5.  
  6. # $mysql_backup_dir
  7. # $seconds_to_save  = $increments_to_save * $seconds_multiplier;
  8. # Just set the seconds_to_save number to
  9. # the correct number of seconds, i.e:
  10. # minute: 60 / hour: 3600 / day: 86400 / week: 604800
  11.  
  12. #my $seconds_to_save = 604800;
  13. my $seconds_to_save = ( 3 * 86400 ) ; # 3 days
  14.  
  15. # call this subroutine with the '$full_dir_name'
  16.  
  17. my ($full_dir_name) = $ARGV[0];
  18.  
  19. if ( not $full_dir_name ) { die "Need a directory name to clean..." };
  20.  
  21. if ( not -e $full_dir_name ) { die "\nCould NOT Clean Old Files - $full_dir_name doesn't exist.\n" };
  22.  
  23. print ("\nCleaning Old Files\n");
  24.  
  25. my $save_time  = time() - $seconds_to_save;
  26. my $deleted_files = 0;
  27.  
  28. print ("\nRemoving Files Older than $seconds_to_save\n");
  29.  
  30. opendir (DIRHANDLE, $full_dir_name) or die "Couldn't open $full_dir_name:$!";
  31.  
  32. # we use $file_prefix to make it safer; we don't want to delete
  33. # any files except those matching the file spec
  34. my $file_prefix="menelvagor";
  35.  
  36. my @filelist = grep { /^$file_prefix/ } readdir(DIRHANDLE);
  37.  
  38. closedir (DIRHANDLE);
  39.  
  40. my @sortlist   = sort(@filelist);
  41.  
  42. my $file_count = @sortlist;
  43. my $file_msg   = "File Count in Backup Dir: $file_count \n\n";
  44. print ($file_msg);
  45.  
  46. # loop through directory
  47. foreach my $infile (@sortlist) {
  48.  
  49.         my $infile_str = $infile;
  50.         $infile     = "$full_dir_name/$infile";
  51.  
  52.         my ($modtime) = (stat($infile))[9];
  53.  
  54.         if ( $modtime < $save_time ) {
  55.                 # file is older, so delete it
  56.                 my $delete_count  = unlink "$infile";
  57.        
  58.                 if ( ! -e $infile ) {
  59.                                         $deleted_files++;
  60.                                         print ("$delete_count File Removed: ($infile_str\)\n");
  61.                                 }
  62.                                 else { print ("\nProblem Removing File: $infile_str\n"); }
  63.                 }
  64.         else { print ("- Keeping: $infile_str\n"); }
  65.  
  66.         } # end of file loop
  67.    
  68. print "\nRemoved $deleted_files Files and/or Directories.\n";
  69.  
  70. ~
  71. ~
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement