We help IT Professionals succeed at work.
Get Started

Efficient symlink removal script #2

Vahan Yerkanian
Last Modified: 2010-03-05
I need to delete subdirectories up to the $dir if the file deleted was the last one in the particular subdir

in other words, if /base/a/c contains only aa.zip and it's outdated, delete the file, rmdir /base/a/c, if there are no more files/directories in /base/a, delete /base/a

Here is the script:

use strict;
use File::Find;

my $now = time;
my $hours = 10; # how old a file gets before it is deleted
my $age = $hours * 60 * 60; # $hours in seconds

my $dir = '/base'; # where to start from

find(\&wanted, $dir);

sub wanted {
return unless -l; # only handle symlinks

my $file_age = (lstat)[8];

 if ($file_age < $now - $age) {
   print "Deleting old file: $_ (", scalar localtime $file_age, ")\n";
 } else {
   print "Not deleting new: $_ (", scalar localtime $file_age, ")\n";
Watch Question
This problem has been solved!
Unlock 1 Answer and 3 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE