Category: | Utility Scripts |
Author/Contact Info | tye |
Description: | Traverses a directory tree deleting any directories that are empty or only contain subdirectories that get deleted. Updated. |
#!/usr/bin/perl -w
use strict;
exit( main( @ARGV ) );
sub DIR() { 1 }
sub FILE() { 2 }
sub dropEmpty {
my( $parent, $dir )= @_;
my $path= "" eq $parent ? $dir : "$parent/$dir";
if( ! chdir( $dir ) ) {
warn "Can't chdir($dir) ", "" eq $parent ? "" : "from $path",
+": $!\n";
return;
}
opendir( DH, "." ) or die "Can't read $path: $!\n";
my $has= 0;
my @dirs;
my $file;
while( defined( $file= readdir(DH) ) ) {
next if $file =~ /^\.\.?$/ && $file !~ /\s/;
if( -l $file || ! -d _ ) {
$has |= FILE;
} else {
$has |= DIR;
push @dirs, $file
}
}
closedir(DH);
if( $has ) {
$has &= ~DIR;
for( @dirs ) {
$has |= DIR
if ! dropEmpty( $path, $_ );
}
}
chdir( ".." ) or die "Can't return up from $path: $!\n";
if( 0 == $has ) {
if( ! rmdir($dir) ) {
$has= 1;
warn "Can't delete empty $path: $!\n";
} else {
warn "Deleted empty directory $path.\n";
}
}
return 0 == $has;
}
sub main {
die "Usage: rmtd dir [...]\nRemoves eMpTy Directories\n"
if ! @_;
for( @_ ) {
dropEmpty( "", $_ );
}
}
|
|
---|
Replies are listed 'Best First'. | |
---|---|
•Re: Remove eMpTy Directories
by merlyn (Sage) on Nov 18, 2002 at 21:57 UTC | |
by jdporter (Paladin) on Nov 19, 2002 at 16:17 UTC | |
by Aristotle (Chancellor) on Nov 20, 2002 at 00:28 UTC |