| Category: | Utility Scripts |
| Author/Contact Info | Sam Tregar <sam@tregar.com> |
| Description: | I like to write articles in POD and preview the results of running pod2html in my web browser. However, this requires me to run a command in a shell everytime I make an edit. Even if it's just 'make' I still can't be bothered.
So I wrote this script to run a command everytime a file changes. It requires Time::HiRes and Getopt::Long. Read the POD for more information. UPDATE: I added code to do a recursive walk when onchange is passed a directory. This enables onchange to watch a whole directory tree. It won't notice new files added though... (Feb 24th 2005) |
#!/usr/bin/perl -w
use strict;
use Time::HiRes qw(sleep);
use Getopt::Long;
use Pod::Usage;
=head1 NAME
onchange - a little program to run a command when a file changes
=head1 SYNOPSIS
Run C<make> command whenever a source file is updated:
$ onchange make *.c *.h &
Run C<pod2html> on a .pod file whenever it is updated:
$ onchange 'pod2html foo.pod > foo.html' foo.pod &
Run C<make> whenever any file in the current directory, or any
directory below, is updated (ignoring files starting with .):
$ onchange make .
=head1 OPTIONS
A couple options are available for your use:
=over
=item --verbose
See the command everytime it runs.
=item --sleep 0.1
Set the granularity of the check for file changes in seconds.
Defaults to 0.5.
=back
=cut
my $verbose = 0;
my $sleep = 0.5;
pod2usage(2) unless
GetOptions('verbose' => \$verbose,
'sleep=f' => \$sleep);
pod2usage("Too few arguements.") unless @ARGV >= 2;
my ($command, @input_files) = @ARGV;
# expand directories in @input_files list with a recursive walk and
# fill in @mtimes with mtimes for files
my (@files, @mtimes);
while (my $f = shift @input_files) {
if (-f $f) {
push(@files, $f);
push(@mtimes, (stat(_))[9]);
} elsif (-d _) {
opendir(DIR, $f);
push @input_files,
map { "$f/$_" }
grep { $_ !~ /^\./ } readdir(DIR);
} else {
die "File '$f' does not exist or is not a file/directory.";
}
}
while(1) {
for (my $x = 0; $x < @files; $x++) {
my $mtime = (stat($files[$x]))[9];
next unless $mtime;
if ($mtime != $mtimes[$x]) {
print STDERR "Running '$command'\n" if $verbose;
system($command);
}
$mtimes[$x] = $mtime;
}
sleep($sleep);
}
|
|
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: onchange - a script to run a command when a file changes
by Zaxo (Archbishop) on Nov 20, 2003 at 21:25 UTC | |
by sauoq (Abbot) on Nov 21, 2003 at 02:01 UTC | |
by samtregar (Abbot) on Nov 21, 2003 at 23:21 UTC |