Bash command to see if any files in dir - test if a directory is empty
This is covered in detail in BashFAQ #004. Notably, use of ls
for this purpose is an antipattern and should be avoided.
shopt -s dotglob # if including hidden files is desired
files=( "$dir"/* )
[[ -e $files || -L $files ]] && echo "Directory is not empty"
[[ -e $files ]]
doesn't actually check if the entire array's contents exist; rather, it checks the first name returned -- which handles the case when no files match, wherein the glob expression itself is returned as the sole result.
Notably:
- This is far faster than invoking
ls
, which requires usingfork()
to spawn a subshell,execve()
to replace that subshell with/bin/ls
, the operating system's dynamic linker to load shared libraries used by thels
binary, etc, etc. [An exception to this is extremely large directories, of tens of thousands of files -- a case in whichls
will also be slow; see thefind
-based solution below for those]. - This is more correct than invoking
ls
: The list of files returned by globbing is guaranteed to exactly match the literal names of files, whereasls
can munge names with hidden characters. If the first entry is a valid filename,"${files[@]}"
can be safely iterated over with assurance that each returned value will be a name, and there's no need to worry about filesystems with literal newlines in their names inflating the count if the localls
implementation does not escape them.
That said, an alternative approach is to use find
, if you have one with the -empty
extension (available both from GNU find and from modern BSDs including Mac OS):
[[ $(find -H "$dir" -maxdepth 0 -type d -empty) ]] || echo "Directory is not empty"
...if any result is given, the directory is nonempty. While slower than globbing on directories which are not unusually large, this is faster than either ls
or globbing for extremely large directories not present in the direntry cache, as it can return results without a full scan.
Finding empty directories
Check whether find <dir> -type f
outputs anything. Here's an example:
for dir in A B C; do
[ -z "`find $dir -type f`" ] && echo "$dir is empty"
done
How do I check if a folder has contents?
You can check if a directory is empty using find
, and processing its output:
#!/bin/sh
target=$1
if find "$target" -mindepth 1 -print -quit 2>/dev/null | grep -q .; then
echo "Not empty, do something"
else
echo "Target '$target' is empty or not a directory"
fi
That is:
- Use
find
to find the first filesystem entry under$target
(-mindepth 1
), print it (-print
), and stop processing (-quit
)- Redirect
stderr
to suppress any error messages (= noise)
- Redirect
- Check if the output of the
find
command is empty usinggrep -q .
grep -q .
will exit after processing at most one character. If it sees a character it exits with success, if it doesn't (its input is empty) then it exits with failure.
- If the output of the
find
command is not empty, then the directory is not empty, andgrep -q .
exits with success. - If the output of the
find
command is empty, then$target
is either an empty directory, or not a directory (does not exist), andgrep -q .
exits with failure.
The reason we have to rely on the stdout
of find
rather than its own exit code directly is that there's no way to make the find
command use distinguishable exit codes in case files were found or not.
Instead of piping to grep -q
, another alternative would be to capture the output of find
and check if it's an empty string or not.
#!/bin/sh
target=$1
if [ "$(find "$target" -mindepth 1 -print -quit 2>/dev/null)" ]; then
echo "Not empty, do something"
else
echo "Target '$target' is empty or not a directory"
fi
Capturing command output like this uses a sub-shell.
I think the solution using grep
is probably faster,
but I haven't tested it.
PHP: What is the best and easiest way to check if directory is empty or not
Use glob
:
if (count(glob("path/*")) === 0 ) { // empty
A nice thing about glob
is that it doesn't return .
and ..
directories.
Related Topics
Mpc/Mpd on Linux: How to Play Local Wav File
Aborting a Blocking Read on Linux
Run Shell Script After Xserver Is Started
Mongodb (Result= Signal, Code = Killed, Signal = Ill
Why Does Utf-8 Text Sort in Different Order Between Os X and Linux
Error Hh604: Error Running JSON-Rpc Server: Error:0308010C:Digital Envelope Routines::Unsupported
Shell Script to Get List of Defined Users on Linux
What Is The Linux Command Line to Check Kernel Space and User Space Memory Used
Shared Library Symbol Conflicts and Static Linking (On Linux)
How to Remove File with Special Characters
Binding on a Port with Netpipes/Netcat
I Need a Binary Comparison Tool for Win/Linux
Linux Telnet Vt100 Return Key Sends ^M
What Exactly Is Program Stack's Growth Direction
Generate Disk Usage Graphs/Charts with Cli Only Tools in Linux