#!/usr/bin/perl # # $Id: dirsyncgz,v 1.2 2007/05/03 05:06:45 cos Exp $ # # syncs files w/names matching a regex from srcdir to destdir, and gzips # # only files whose modification time is more recent than the # corresponding gzip'ed file will be copied, and if a file has been # deleted from the srcdir, the corresponding gzip'ed file will be # deleted from the destdir # # Contributions/suggestions/bugs to: Ofer Inbar # # All my scripts distributed under the terms of Larry Wall's excellent # Artistic License: http://language.perl.com/misc/Artistic.html my $srcdir = "/src/directory"; my $destdir = "/destination/directory"; my $basename = "^basename-"; # regexes okay! opendir SRCDIR, $srcdir or die "$0: can't open directory $srcdir: $!\n"; foreach $file ( sort grep { /$basename/ && -f "$srcdir/$_" } readdir(SRCDIR) ) { next unless ((stat("$srcdir/$file"))[9] > (stat("$destdir/$file.gz"))[9]); print "Copying $srcdir/$file to $destdir\n"; system("cp -p $srcdir/$file $destdir") == 0 or warn "$0: cp -p $srcdir/$file $destdir failed: $?\n" and next; system("gzip -f $destdir/$file") == 0 or warn "$0: gzip -f $destdir/$file failed: $?\n"; } # now delete from the destdir any files deleted from the srcdir opendir DESTDIR, $destdir or die "$0: can't open directory $destdir: $!\n"; foreach $savedfile ( sort grep { /$basename/ && -f "$destdir/$_" } readdir(DESTDIR) ) { $savedfile =~ s/.gz$//; next if -f "$srcdir/$savedfile"; print "Deleting $savedfile from $destdir\n"; unlink "$destdir/${savedfile}.gz" or unlink "$destdir/$savedfile" or warn "$0: error deleting $savedfile: $!\n"; }