code_junkie

Monitor a set of files for changes and execute a command on them when they do

Nov 13th, 2011
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. watching FILE+ do COMMAND [ARGS] (and COMMAND [ARGS])*
  2.  
  3. > watching foo.txt bar.txt do scp {} somewhere.com:. and echo moved {} to somewhere
  4.  
  5. > watching foo.c do gcc foo.c and ./a.out
  6.  
  7. #!/usr/bin/perl
  8. # Run some commands whenever any of a set of files changes (see USAGE below).
  9. # Example:
  10. # ./watching.pl foo.txt bar.txt do scp foo.txt remote.com:. and cat bar.txt
  11. # To only do something to the file that changed, refer to it as {}.
  12.  
  13. $| = 1; # autoflush
  14.  
  15. my $p = position("do", @ARGV); # position of 1st occurrence of "do" in @ARGV.
  16. if (@ARGV < 3 || $p == -1 || !($p >= 1 && $p < $#ARGV)) {
  17. die "USAGE: watching FILE+ do COMMAND [ARGS] (and COMMAND [ARGS])*n";
  18. }
  19.  
  20. my $cmdstr = join(' ', splice(@ARGV, $p+1)); # grab stuff after the "do"
  21. my @cmds = split(/s+ands+/, $cmdstr);
  22. pop(@ARGV); # remove the "do" on the end.
  23. my @targets = @ARGV;
  24. print "Watching {", join(' ', @targets), "} do (", join('; ', @cmds), "):n";
  25.  
  26. # initialize the %last hash for last mod time of each file.
  27. for my $t (@targets) {
  28. ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
  29. $atime,$mtime,$ctime,$blksize,$blocks) = stat($t);
  30. $last{$t} = $mtime;
  31. }
  32.  
  33. my $i = 1;
  34. while(1) {
  35. if($i % (45*60) == 0) { print "."; }
  36.  
  37. for my $t (@targets) {
  38. ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
  39. $atime,$mtime,$ctime,$blksize,$blocks) = stat($t);
  40.  
  41. if ($mtime != $last{$t}) {
  42. print "nCHANGE DETECTED TO $tn";
  43. for (@cmds) { my $tmp = $_; $tmp =~ s/{}/$t/g; system($tmp); }
  44. $last{$t} = $mtime;
  45. }
  46. }
  47. sleep(1);
  48. $i++;
  49. }
  50.  
  51.  
  52. # Call like so: position($element, @list).
  53. sub position {
  54. my $x = shift;
  55. if(@_==0) { return -1; }
  56. if($x eq $_[0]) { return 0; }
  57. shift;
  58. my $p = position($x,@_);
  59. if($p==-1) { return -1; }
  60. return 1+$p;
  61. }
Add Comment
Please, Sign In to add comment