Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast test if directory is empty

What is the fastest way to test if a directory is empty?

Of course I can check the length of

list.files(path, all.files = TRUE, include.dirs = TRUE, no.. = TRUE)

but this requires enumerating the entire contents of the directory which I'd rather avoid.

EDIT: I'm looking for portable solutions.

EDIT^2: Some timings for a huge directory (run this in a directory that's initially empty, it will create 100000 empty files):

system.time(file.create(as.character(0:99999)))
#    user  system elapsed 
#   0.720  12.223  14.948 
system.time(length(dir()))
#    user  system elapsed 
#   2.419   0.600   3.167 
system.time(system("ls | head -n 1"))
# 0
#   user  system elapsed 
#  0.788   0.495   1.312 
system.time(system("ls -f | head -n 3"))
# .
# ..
# 99064
#    user  system elapsed 
#   0.002   0.015   0.019 

The -f switch is crucial for ls, it will avoid the sorting that will take place otherwise.

like image 926
krlmlr Avatar asked Feb 05 '14 12:02

krlmlr


People also ask

How check if directory is empty?

File. list() is used to obtain the list of the files and directories in the specified directory defined by its path name. This list of files is stored in a string array. If the length of this string array is greater than 0, then the specified directory is not empty.

How do you check whether a directory is empty or not in shell script?

There are many ways to find out if a directory is empty or not under Linux and Unix bash shell. You can use the find command to list only files. In this example, find command will only print file name from /tmp. If there is no output, directory is empty.

How do you check if a folder is empty in Windows?

You could use List folder action to check if there are any items in the specified folder, including files and folders. Then configure length() function to determine if any elements are included in Body. If the result is 0, it means that this is an empty folder, which does not contain any files and folders.


1 Answers

How about if(length(dir(all.files=TRUE)) ==0) ?

I'm not sure what you qualify as "fast," but if dir takes a long time, someone is abusing your filesystem :-(.

like image 53
Carl Witthoft Avatar answered Sep 30 '22 10:09

Carl Witthoft