From a shell script, how do I check if a directory contains files?
Something similar to this
if [ -e /some/dir/* ]; then echo "huzzah"; fi;
but which works if the directory contains one or several files (the above one only works with exactly 0 or 1 files).
The solutions so far use
ls
. Here's an all bash solution:This tells me if the directory is empty or if it's not, the number of files it contains.
This may be a really late response but here is a solution that works. This line only recognizes th existance of files! It will not give you a false positive if directories exist.
I would go for
find
:This checks the output of looking for just files in the directory, without going through the subdirectories. Then it checks the output using the
-z
option taken fromman test
:See some outcomes:
Empty dir:
Just dirs in it:
A file in the directory:
A file in a subdirectory:
Try with command find. Specify the directory hardcoded or as argument. Then initiate find to search all files inside the directory. Check if return of find is null. Echo the data of find
Simple answer with bash: