Novell Home

Recursive Directory Remove

From Developer Community

This short perl function will recursively delete a directory and everything in it. All directories and file will be removed including the specified directory.

Function

#!/usr/bin/perl

cleanup("/tmp");

sub cleanup {
        my $dir = shift;
	local *DIR;

	opendir DIR, $dir or die "opendir $dir: $!";
	for (readdir DIR) {
	        next if /^\.{1,2}$/;
	        my $path = "$dir/$_";
		unlink $path if -f $path;
		cleanup($path) if -d $path;
	}
	closedir DIR;
	rmdir $dir or print "error - $!";
}

--Paul Jones

Novell® Making IT Work As One

© 2009 Novell, Inc. All Rights Reserved.