Forum Moderators: coopster & phranque

Message Too Old, No Replies

Need simple script to delete all files in a cache folder

         

EsterA

3:13 am on Jan 8, 2007 (gmt 0)

10+ Year Member


I need simple script to delete all files in a cache folder. I found this one out there but unfortunately it didn't work for me.
I know nothing about Perl, but I know I got the path to Perl right. The script was named autodelete.pl and placed in the same folder as the files that it should delete. It should delete only the files with 'cache' as part of filename. Then I run it with a crontab. But no files were deleted. Could someone tell me why?

#! /usr/bin/perl
$word_to_delete = "cache";

opendir (DIR,".");
@files = grep(/$word_to_delete/, readdir (DIR));
closedir (DIR);

foreach $file (@files)
{
unlink $file;
}

perl_diver

6:35 pm on Jan 8, 2007 (gmt 0)

10+ Year Member



try using the actual directory just to test if it's something to with running it from a cron:

opendir (DIR,"path/to/dir");

if so you can use Cwd to get the cwd:

#! /usr/bin/perl
use Cwd;
my $dir = getcwd;
my $word_to_delete = "cache";
opendir (DIR,$dir);
@files = grep(/$word_to_delete/, readdir (DIR));
closedir (DIR);
foreach $file (@files)
{
unlink "$dir/$file";
}

remember, deleting files is "dangerous" so test in a dummy directory with dummy files first.

phranque

11:26 pm on Jan 8, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



you may have a permission problem.
it's best to write the error to see what's happening.
you can also do some wildcarding in a single unlink to make things more efficient, given the above caveat.

unlink (glob("$directory_path/*$word_to_delete*")) or warn "can't delete files: $!";

EsterA

9:57 am on Jan 10, 2007 (gmt 0)

10+ Year Member



Thanks for your answers, but you are talking to a novice here, so I'm sorry to say I don't know what to use of what you are writing.

Do you mean I should write the script like this:

#! /usr/bin/perl
use Cwd;
my $dir = getcwd;
my $word_to_delete = "cache";
opendir (DIR,$dir);
@files = grep(/$word_to_delete/, readdir (DIR));
closedir (DIR);
foreach $file (@files)
{
unlink "$dir/$file";
}

or should I include this line somewhere:

opendir (DIR,"path/to/dir");

alien

6:48 pm on Jan 10, 2007 (gmt 0)

10+ Year Member



Wouldn't it be easier to use the rm command? Or make an alias to it?

phranque

1:22 am on Jan 11, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



try this script:

#! /usr/bin/perl
use Cwd;
my $dir = getcwd;
my $word_to_delete = "cache";
unlink (glob("$dir/*$word_to_delete*")) or warn "can't delete files: $!";