Hennessy Consulting Inc.
Phone: (303) 265-9964
Email: chris@hennessy-consulting.com
Hennessy Consulting Inc
Backup_file.pl     

 

Backup_file.pl                                   



#!/usr/local/bin/perl


###################################################################
#
# Purpose: This program moves the indicated file to a new
# name which is the same as the original, with 
# a date time stamp appended to the end(ie.
# *.MMDD.HHMMSS). 
#
# Inputs: filename - file to be backed up
#
# Options: -d <directory> -use directory instead of cwd
# -r <save_count> -keep save_count most recent
# files, deleteing oldest.
# default is 10.
#
# Author: Chris Hennessy
###################################################################
$INC[0] = "/admin/perl5.005_02/lib/";
require 'getopts.pl';
$ROLL_CNT = 10;

&Getopts('d:r:');

if ( $#ARGV != 0 ) {
print "Usage: $0 [-d directory][-r save_count] <filename>\n\n";
exit(1);
}

$ROLL_CNT = $opt_r if $opt_r > 0;

if ($opt_d && -d $opt_d) {
$backup_dir = $opt_d;
}
elsif ($opt_d) {
printf "%s - invalid directory path", $opt_d;
exit(1);
}
$backup_dir = "." unless $backup_dir; 

$bfile = $ARGV[0];

die "$backup_dir/$bfile - invalid file name\n\n" unless -e "$backup_dir/$bfile";
die "$backup_dir/$bfile not a readable file\n\n" unless -r "$backup_dir/$bfile";

#printf "backing up file: %s\n", $bfile;
&do_back($backup_dir);
exit(0);

sub do_back {
local($dir, $nlink) = @_;
local($dev, $ino, $mode, $subcount);

($dev, $ino, $mode, $nlink) = stat($dir) unless $nlink;

opendir(DIR, $dir) || die "Can't open $dir";
local(@filenames) = readdir(DIR);
closedir(DIR);

for (@filenames) {
next if substr($_, 0, length($bfile)) ne $bfile;
next if $_ eq $bfile;
next if -d "$dir/$_";
push(@matched, $_);
}

@matched = sort(@matched);
($sec, $min, $hour, $mday, $mon) = localtime(time);
$mon = "0".$mon if ++$mon < 10;
$mday = "0".$mday if $mday < 10;
$hour = "0".$hour if $hour < 10;
$min = "0".$min if $min < 10;
$sec = "0".$sec if $sec < 10;
$date_stuff = ".".$mon.$mday.".".$hour.$min.$sec;
$newname = $bfile.$date_stuff;
rename($dir."/".$bfile, $dir."/".$newname);
unlink($dir."/".$matched[0]) if $#matched + 2 >= $ROLL_CNT;
}