multiple_backups.pl 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. #!/usr/bin/perl
  2. # Author: Trizen
  3. # Date: 11 September 2023
  4. # https://github.com/trizen
  5. # Create multiple backups of a list of filenames and update them as necessary.
  6. use 5.036;
  7. use Getopt::Long;
  8. use File::Basename qw(basename);
  9. use File::Copy qw(copy);
  10. use File::Spec::Functions qw(catfile curdir);
  11. my $backup_dir = curdir();
  12. sub usage ($exit_code = 0) {
  13. print <<"EOT";
  14. usage: $0 [options] [filenames]
  15. options:
  16. --dir=s : directory where to save the backups (default: $backup_dir)
  17. EOT
  18. exit($exit_code);
  19. }
  20. GetOptions("d|dir=s" => \$backup_dir,
  21. 'h|help' => sub { usage(0) },)
  22. or die("Error in command line arguments\n");
  23. my %timestamps = (
  24. "1h" => 1 / 24,
  25. "1d" => 1,
  26. "3d" => 3,
  27. "30d" => 30,
  28. "1y" => 365,
  29. );
  30. @ARGV || usage(2);
  31. foreach my $file (@ARGV) {
  32. say ":: Processing: $file";
  33. foreach my $key (sort keys %timestamps) {
  34. my $checkpoint_time = $timestamps{$key};
  35. my $backup_file = catfile($backup_dir, basename($file) . '.' . $key);
  36. if (not -e $backup_file or ((-M $backup_file) >= $checkpoint_time)) {
  37. say " > writing backup: $backup_file";
  38. copy($file, $backup_file)
  39. or warn "Can't copy <<$file>> to <<$backup_file>>: $!";
  40. }
  41. }
  42. }