http://qs321.pair.com?node_id=1209381


in reply to Clean Up Empty Directories

use 5.14.2; use warnings; our $VERSION = "1.01 - 20180217"; my $cmd = $0 =~ s{.*/}{}r; sub usage { my $err = shift and select STDERR; print "usage: $cmd [ --rmdir ] [ dir ... ]\n"; exit $err; } # usage use Getopt::Long qw(:config bundling nopermute); GetOptions ( "help|?" => sub { usage (0) }, "V|version" => sub { say "$cmd [$VERSION]"; exit 0; }, "d|delete|rm|rmdir" => \my $opt_d, ) or usage (1); use File::Find; no warnings "File::Find"; my @dir = @ARGV ? @ARGV : ("."); grep { ! -d $_ } @dir and usage (1); finddepth (sub { ! -d $_ || m/^\.\.?$/ and return; my ($dh, @d); unless (opendir $dh, $_ and @d = readdir $dh) { warn "Cannot read $File::Find::name\n"; return; } closedir $dh; if (@d == 2) { print "$File::Find::name\n"; $opt_d and rmdir $_; } }, @dir);

Used and tested on HP-UX, AIX, and Linux. Don't know if it works on Windows.

The find/exec has the problem that it needs to be run many times to cope with deep empty trees, and I had trees of 20+ levels on systems with 4Tb. It is no fun to run that many times.

Another advantage of above script is that it first reports. Actually removing is an option.

No warnings File::Find, because I don't care if folders are removed while running or symbolic links still exist or NFS (if a user chooses to do so) falls inactive.


Enjoy, Have FUN! H.Merijn

Replies are listed 'Best First'.
Re^2: Clean Up Empty Directories
by GotToBTru (Prior) on Feb 19, 2018 at 19:21 UTC

    Too much typing! ;) I use my own as part of a space recovery script that runs in background, so I didn't plan or allow for any interaction. The du command often takes more than 20 minutes to return in my application.

    But God demonstrates His own love toward us, in that while we were yet sinners, Christ died for us. Romans 5:8 (NASB)