Reputation: 21
I'm trying to run a perl script from crontab but I'm having difficulty. It works perfectly when I run it from the command line. I've searched and seen various answers about Environment etc and specifying full paths but I'm not sure if I'm doing it correctly. Below is the script
#!/usr/bin/perl
$ENV{'PATH'} = '/usr/bin:/usr/sbin/usr/local/bin';
use strict;
my $TG_Stats_directory = "/export/home/SonusNFS/TG_Stats";
opendir TG_Stats, $TG_Stats_directory;
my @GSX_directories = readdir TG_Stats;
foreach my $subdir (@GSX_directories) {
opendir GSX, $subdir;
my @csv_listing = readdir GSX;
foreach my $file (@csv_listing){
if ($file =~ /\.csv/){
unlink $TG_Stats_directory."/".$subdir."/".$file;
}
}
close GSX;
}
close TG_Stats;
Below is the crontab entry.
25 03 * * * /usr/bin/perl /export/home/SonusNFS/TG_Stats/rmdir.pl 2>/tmp/cronerrors.txt
What am I missing? What do I need to add to get it working in Cron?
Upvotes: 0
Views: 2296
Reputation: 3498
Some pointers:
> $ENV{'PATH'} = '/usr/bin:/usr/sbin/usr/local/bin';
$ENV{PATH} = '/usr/bin:/usr/sbin:/usr/local/bin';
> use strict;
don't forget warnings:
use warnings;
> my $TG_Stats_directory = "/export/home/SonusNFS/TG_Stats";
> opendir TG_Stats, $TG_Stats_directory;
better use lexical DIR-handles:
opendir my $TG_Stats... or die $!;
> my @GSX_directories = readdir TG_Stats;
You do realize that '.' and '..' are in your list now, do you?
my @GSX_directories = grep !/^\.\.?$/, readdir TG_Stats;
> foreach my $subdir (@GSX_directories) {
> opendir GSX, $subdir;
This fails UNLESS your current working directory IS $TG_Stats_directory!:
opendir my $GSX, "$TG_Stats_directory/$subdir" or die $!;
> my @csv_listing = readdir GSX;
> foreach my $file (@csv_listing){
> if ($file =~ /\.csv/){
don't you mean files ENDING in .csv?
if ( $file =~ /\.csv$/ ) {
> unlink $TG_Stats_directory."/".$subdir."/".$file;
> }
}
> close GSX;
closedir $GSX;
> }
> close TG_Stats;
closedir $TG_Stats;
HTH, Paul
Upvotes: 0
Reputation: 21
It appears that the directory that I run it from matters. When I run it from root like this:
# cd /
# perl /export/home/SonusNFS/TG_Stats/rmdir.pl
I get a completely different set of results to this:
# cd /export/home/SonusNFS/TG_Stats/
# perl rmdir.pl
With that in mind, I added this to the script:
my $directory = "/export/home/SonusNFS/TG_Stats";
chdir($directory) or die "Can't chdir to $directory $!";
It finally ran from cron. Still don't understand why the results were different even though I specified the path in the first scenario.
Thanks for all the answers though guys. My answer isn't even a real answer, just a workaround
Upvotes: 2