Question

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

Was it helpful?

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");
}

OTHER TIPS

You can use backticks in perl as well.

$ perl -e"print qq(`date "+%Y%m%d"`)"

removing a file from perl can be done with unlink().

Checking a file for existence is done with e.g.

if ( -e $filename ) { die("File $filename exists") };

Update:

You can also accomplish it with readdir and using a regular expression on the filename.

use Time::localtime

opendir(DIR, "/cygdrive/d/test/") || die("Error");
$backup_exists = 0;
$prefix = "CATN0000.";
while ($f = readdir(DIR)) {
  $today_timestamp = sprintf('%4d%02d%02d', localtime->year()+1900, localtime->mon()+1, localtime->mday());
  if ( $f =~ /$prefix$today_timestamp/ ) {
    $backup_exists = 1;
  }
}
closedir(DIR);

if ( $backup_exists ) {
  print "Backup exists\n";
} else {
  print "Backup does not exist\n";
}

update 2: but the glob() version above is way more eficcient. Use that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top