gpt4 book ai didi

command-line - 监视一组文件的更改并在更改时对其执行命令

转载 作者:行者123 更新时间:2023-12-04 05:29:47 26 4
gpt4 key购买 nike

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

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

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

最佳答案

#!/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;
}

关于command-line - 监视一组文件的更改并在更改时对其执行命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/393176/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com