#!/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( "", $_ ); } }