Search code examples
perlfilelocaltime

How to check a file like this


I take backups on my db every day , The file names will be like shown below

AWDRT.0.db2inst1.NODE0000.CATN0000.20130312095740.001
AWDRT.0.db2inst1.NODE0000.CATN0000.20130313100330.001
GSRTC.0.db2inst1.NODE0000.CATN0000.20130313102253.001

How do i check if the backup is taken today or not , if seen after the CATN0000 the timestamp is appended i.e., YYYYMMDD . So i can check for the backup file exists

In shell i used to do it like

/home/ftpusr/backup/AWDRT.0.db2inst1.NODE0000.CATN0000.`date +%Y%m%d`*

How do i do this in perl and how can i purge old backup which i do in shell like below

/home/ftpusr/backup/AWDRT.0.db2inst1.NODE0000.CATN0000.`date +%Y%m%d -d "$i days ago"`

Help is appreciated


Solution

  • First change dir to where the backups are (to be added to both scripts)

    chdir ('/home/backups/vital');
    

    To list today's backup (local time)

    $now = time();
    ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($now);
    $ymd = sprintf("%4d%02d%02d", $year+1900, $mon+1, $mday);
    
    @backup = glob("*.CATN0000.$ymd*");
    
    if ($#backup >= 0) {
      print("Backup at $ymd: @backup\n");
    }
    else {
      print("No backup at $ymd\n");
    }
    

    Then to find and remove a file of n days ago (if several files match, only the first one in the list is removed)

    $daysago = 3; # 3 days ago
    $now = time();
    
    ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($now - $daysago*3600*24);
    $old = sprintf("%4d%02d%02d", $year+1900, $mon+1, $mday);
    
    @oldbackup = glob("*.CATN0000.$old*");
    
    if ($#oldbackup >= 0) {
      print("Old Backup at $old: @oldbackup - removing (first one)\n");
      unlink( $oldbackup[0] );
    }
    else {
      print("No old backup at $old\n");
    }