13

What is an easy way to test if a folder is empty in perl? -s, and -z are not working.

Example:

#Ensure Apps directory exists on the test PC.
if ( ! -s $gAppsDir )
{ 
    die "\n$gAppsDir is not accessible or does not exist.\n"; 
}

#Ensure Apps directory exists on the test PC.
if ( ! -z $gAppsDir )
{ 
    die "\n$gAppsDir is not accessible or does not exist.\n"; 
}

These above, do not work properly to tell me that the folder is empty. Thanks!


Thanks all! I ended up using:

sub is_folder_empty { my $dirname = shift; opendir(my $dh, $dirname) or die "Not a directory"; 
return scalar(grep { $_ ne "." && $_ ne ".." } readdir($dh)) == 0; }
0

8 Answers 8

26

A little verbose for clarity, but:

sub is_folder_empty {
    my $dirname = shift;
    opendir(my $dh, $dirname) or die "Not a directory";
    return scalar(grep { $_ ne "." && $_ ne ".." } readdir($dh)) == 0;
}

Then you can do:

if (is_folder_empty($your_dir)) {
    ....
}
8
  • 4
    re "Not a directory": or doesn't exist or don't have permission, etc. how about or die "$dirname: $!"
    – ysth
    Dec 20, 2010 at 20:27
  • 5
    @Zaid: You seem to have confused 'clarity' and 'brevity'. Also, touch dir/.... fools your regular expression.
    – aschepler
    Dec 20, 2010 at 20:34
  • 1
    Clarity and brevity is good. The solution does read all the file names in the directory, whereas at most three entries are needed ('.' and '..' probably appear first, and the next name indicates that the directory is not empty. Fixing that defeats clarity, though. Dec 21, 2010 at 22:38
  • 3
    Shouldn't the directory handle be closed? closedir($dh)
    – Andre
    May 13, 2014 at 8:59
  • 1
    @Andre perl will close the filehandle once $dh goes out of scope, i.e. when is_folder_empty returns.
    – josch
    Jul 27, 2018 at 11:39
5

Using grep { ! /^[.][.]?\z/ } readdir $dir_h can be problematic for performance in case the check is done many times and some directories may have many files.

It would be better to short-circuit the moment a directory entry other than . or .. is found.

On Windows XP with ActiveState perl 5.10.1, the following sub seems to be twice as fast as the grep approach on my $HOME with 100 entries:

sub is_dir_empty {
    my ($dir) = @_;

    opendir my $h, $dir
        or die "Cannot open directory: '$dir': $!";

    while ( defined (my $entry = readdir $h) ) {
        return unless $entry =~ /^[.][.]?\z/;
    }

    return 1;
}
1
  • @ysth return ! defined List::Util::first { $_ !~ /^[.][.]?\z/ } readdir $h; the disadvantage of that solution is, that it will read the whole directory entries to a list first. This can be slow for directories with many members.
    – josch
    Jul 27, 2018 at 11:30
3

Or without any grepping or regular expressions - which rules out any chance of weird file names accidentally getting though. Plus slightly faster is my testing.

#!/usr/bin/perl
use strict;
use warnings;

sub is_dir_empty {
    return -1 if not -e $_[0];   # does not exist
    return -2 if not -d $_[0];   # in not a directory
    opendir my $dir, $_[0] or    # likely a permissions issue
        die "Can't opendir '".$_[0]."', because: $!\n";
    readdir $dir;
    readdir $dir;
    return 0 if( readdir $dir ); # 3rd times a charm
    return 1;
}

my @folders = qw( ./ ./empty ./hasonefile ./hastwofiles ./doesnotexist ./afile );
for my $folder ( @folders ) {
    print "Folder '$folder' ";
    my $rc = is_dir_empty( $folder );
    if( $rc == -1 ) {
        print "does not exist\n";
    } elsif( $rc == -2 ) {
        print "is not a directory\n";
    } elsif( !$rc ) {
        print "is not empty\n";
    } else {
        print "is empty\n";
    }
}

Pretty simple. If you get three valid responses from a call to readdir, then you know there must be a file in there. Regardless of what name the file may have - or the order in which the files are being processed. Would have preferred something called 'is_dir_used' as I personally don't like the double-negative function name and return value.

5
  • 1
    This should be the accepted solution. It is the only solution that does not read the whole directory content and also doesn't apply regexes that are not needed (as proven by this solution). I guess people might be worried, because this code snippet is longer than the others but that is only because in addition this solution also shows proper error handling with is another advantage in my opinion.
    – josch
    Jul 27, 2018 at 11:35
  • @josch no, the tests for names to ignore are needed. Not all filesystems will have a .. in every directory, for example.
    – ysth
    Jul 27, 2018 at 15:11
  • 1
    @ysth Isn't the .. entry a property of the OS and not of the file system? Which ones do not have that?
    – josch
    Jul 30, 2018 at 15:31
  • 1
    @josch An ISO compliant or compatible OS, should support both the '.' and '..' for any mountable filesystem, and that covers just about every modern OS there is. I have seen and used systems that did not support these - perhaps 25+ years ago, and none of those systems supported Perl - so this solution should be OK today.
    – Jim Black
    Nov 20, 2018 at 18:11
  • It's safer to check the third return value for definedness -- if readdir $dh may fail if the directory happens to contain a file called 0.
    – xebtl
    Jan 18, 2021 at 20:55
1

There is also File::List from cpan. It's overkill here, but can be handy for slightly more complex requests like test if a directory is empty with the meaning it contains only empty directories (ie: not files).

0

Here is a more consise algorithm using Perl v5.12 (from circa 2010). At most, three reads of the directory are made.

  • It does NOT read the whole directory.
  • It handles non-Unix filesystems that do not have '..'; See 'find' '-noleaf'

Desc: return true if empty, false if not empty; die if opendir() error

sub is_dir_empty {
    use 5.012;      # so readdir assigns to $_ in a lone while test
    local($_);      # prevent side effects

    my $dir = shift // die "arg missing";

    opendir my $dh, $dir or die "opendir(..,$dir): $!";

    while ( readdir $dh ) {
        return 0  if ! /^ [.][.]? $/x;
    }

    return 1;
} # is_dir_empty()
-1

Credit to DevShed

if (scalar <directory/*>) {print qq|File Exists\n|}

Edit

To include hidden files:

@arr = <directory/* directory/.*>;
@arr = grep {!/^directory/[.]{1,2}$/} @arr;
if (@arr) { print qq|File or Directory Exists\n| }

Please read the comments as there have been good points made. Despite the negative points this answer has received, it is still correct.

7
  • 1
    bad bad bad. never use glob in scalar context unless you really know what you are doing. that line, if called repeatedly, will return true once for each thing in directory, then will return false once, then start over.
    – ysth
    Dec 20, 2010 at 20:32
  • 1
    I don't think that's true. I think it will stop at the first file found, as mentioned in the forum it's similar to -e and equivalent to calling w/o scalar, both will stop at the first file found. never use glob in scalar context unless you really know what you are doing in this regard it's perfectly safe. Not doing something for the sake of not doing it is bad advice.
    – vol7ron
    Dec 20, 2010 at 20:43
  • 2
    try it. the following will print File Exists twice, not three times: mkdir directory; touch directory/a; touch directory/b; perl -we'for(1..3){if (scalar <directory/*>) {print qq|File Exists\n|}}'
    – ysth
    Dec 20, 2010 at 20:49
  • 4
    a correct way to do it would be if (()=<directory/*>) but still suffers the flaw of not noticing files like directory/.foo
    – ysth
    Dec 20, 2010 at 20:56
  • ysth: that is true and I never denied that. I also agree, you should know what you're doing, but this is a perfect valid way to test if a directory is empty (it does not check for hidden files as you mentioned). -- your example is for a loop, however if you did $x=<directory/*>;$y=<directory/*>; then $x and $y would both be the same thing, the handle is recalled, otherwise (in a loop) the handle is left open and retrieves the next thing, so instead of for its better to use while - an end of file will be reached.
    – vol7ron
    Oct 3, 2012 at 1:14
-1
opendir(DIR,"DIR PATH") or die "Unable to open directory \"DIR PATH\" \n";
my @drList = readdir(DIR);
close(DIR);
if( grep(/\w/,@drList) ){ print "Not Empty\n" }
else { print "Empty\n" }
1
  • This will fail on directories that are not-empty but contain files that do not match /\w/.
    – josch
    Jul 27, 2018 at 11:19
-1
  sub is_folder_empty {
        my $dirname = shift;
        my @files = File::Find::Rule->file()->name('*')->maxdepth(1)->in("$dirname");
        return $#files < 0;
    }
1
  • This will fail for non empty directories containing files that do not match *. For example files that start with a dot.
    – josch
    Jul 27, 2018 at 11:22

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.