4

我想到的(命令行)界面是这样的:

watching FILE+ do COMMAND [ARGS] (and COMMAND [ARGS])*

其中任何出现的“ {}COMMAND都将替换为更改的文件的名称。请注意,“ do”和“ and”是关键字。

例如:

> watching foo.txt bar.txt do scp {} somewhere.com:. and echo moved {} to somewhere

或者:

> watching foo.c do gcc foo.c and ./a.out

不过,我并不喜欢那个界面。我将添加我的脚本作为答案,看看是否有人有更好的方法或改进它的方法。

4

4 回答 4

2
#!/usr/bin/perl
# Run some commands whenever any of a set of files changes (see USAGE below).
# Example:
# ./watching.pl foo.txt bar.txt do scp foo.txt remote.com:. and cat bar.txt
# To only do something to the file that changed, refer to it as {}.

$| = 1;  # autoflush

my $p = position("do", @ARGV); # position of 1st occurrence of "do" in @ARGV.
if (@ARGV < 3 || $p == -1 || !($p >= 1 && $p < $#ARGV)) {
  die "USAGE: watching FILE+ do COMMAND [ARGS] (and COMMAND [ARGS])*\n";
}

my $cmdstr = join(' ', splice(@ARGV, $p+1));  # grab stuff after the "do"
my @cmds = split(/\s+and\s+/, $cmdstr);
pop(@ARGV);  # remove the "do" on the end.
my @targets = @ARGV;
print "Watching {", join(' ', @targets), "} do (", join('; ', @cmds), "):\n";

# initialize the %last hash for last mod time of each file.
for my $t (@targets) {
  ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
   $atime,$mtime,$ctime,$blksize,$blocks) = stat($t);
  $last{$t} = $mtime;
}

my $i = 1;
while(1) {
  if($i % (45*60) == 0) { print "."; }

  for my $t (@targets) {
    ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
     $atime,$mtime,$ctime,$blksize,$blocks) = stat($t);

    if ($mtime != $last{$t}) {
      print "\nCHANGE DETECTED TO $t\n";
      for (@cmds) { my $tmp = $_; $tmp =~ s/\{\}/$t/g; system($tmp); }
      $last{$t} = $mtime;
    }
  }
  sleep(1);
  $i++;
}


# Call like so: position($element, @list).
sub position {
  my $x = shift;
  if(@_==0) { return -1; }
  if($x eq $_[0]) { return 0; }
  shift;
  my $p = position($x,@_);
  if($p==-1) { return -1; }
  return 1+$p;
}
于 2008-12-25T20:49:18.627 回答
1

请检查inotify工具

于 2008-12-26T20:35:36.577 回答
1

我刚刚发现这个every_change脚本是用 perl 编写的,这与我在答案中发布的非常相似。

该脚本非常适合代码开发。每次更改时监视文件并运行它(或其他东西)。在一个窗口中编写代码,然后在另一个窗口中观察它自动执行。

所以基本上每次文件更改时它都会做一些事情。

于 2008-12-26T22:03:40.083 回答
1

您可以使用entr,例如

ls foo.txt bar.txt | entr sh -c 'rsync -vuar *.txt somewhere.com:. && echo Updated'

不幸的是,您无法检查哪个文件已更改,但使用rsync -u会自动跳过未更改的文件。

这是第二个例子:

ls foo.c | entr sh -c 'gcc foo.c && ./a.out'

或简单地使用make,例如

ls -d * | entr sh -c 'make && make test'

要查看目录的更改,请使用-d包装在 shell 循环中的参数,例如:

while true; do find path/ | entr -d do_stuff; done
于 2016-07-06T17:44:24.850 回答