Bash Shell Check Whether a Directory is Empty or Not
Q. How do I check whether a directory is empty or not under Linux / UNIX using a shell script? I'd like to take some action if directory is empty.
A. There are many ways to find out if a directory is empty or not under UNIX / Linux bash shell. You can use find command to list only files. For example, following find command will only print file name from /tmp. If there is no output, directory is empty.
$ find "/tmp" -type f -exec echo Found file {} \;
Output:
Found file /tmp/_.c Found file /tmp/orbit-vivek/bonobo-activation-server-ior Found file /tmp/orbit-vivek/bonobo-activation-register.lock Found file /tmp/_.vsl Found file /tmp/.X0-lock Found file /tmp/.wine-1000/server-802-35437d/lock Found file /tmp/.wine-1000/cxoffice-wine.lock Found file /tmp/ksocket-vivek/Arts_PlayObjectFactory Found file /tmp/ksocket-vivek/Arts_SimpleSoundServer Found file /tmp/ksocket-vivek/secret-cookie Found file /tmp/ksocket-vivek/Arts_AudioManager Found file /tmp/ksocket-vivek/Arts_SoundServer Found file /tmp/ksocket-vivek/Arts_SoundServerV2 Found file /tmp/vcl.XXf8tgOA Found file /tmp/Tracker-vivek.6126/cache.db Found file /tmp/gconfd-vivek/lock/ior
However, the simplest and most effective way is to use ls command with -A option:
$ [ "$(ls -A /path/to/directory)" ] && echo "Not Empty" || echo "Empty"
or
$ [ "$(ls -A /tmp)" ] && echo "Not Empty" || echo "Empty"
Use if..else.fi in a shell script:
#!/bin/bash
FILE=""
DIR="/tmp"
# init
# look for empty dir
if [ "$(ls -A $DIR)" ]; then
echo "Take action $DIR is not Empty"
else
echo "$DIR is Empty"
fi
# rest of the logic
Subscribe to our free e-mail newsletter or RSS feed to get all updates.
You can Email this page to a friend.
Related Other Helpful FAQs:
- Linux how do I remove all empty directories?
- Delete or remove a directory Linux command
- Ubuntu Linux: Delete directory command in Terminal
- Howto delete empty lines using sed command under Linux / UNIX
- Linux Force fsck on the next reboot or boot sequence
Discussion on This FAQ
Leave a Reply
We encourage your comments, and suggestions. But please stay on topic, be polite, and avoid spam. Thank you very much for stopping by our site!
Tags: check if dir is empty, find_command, linux bash, ls_command, shell script



November 23rd, 2007 at 7:36 pm
Seems to me that using ls is not required - in fact, it is doable within the shell alone:
set - `echo .* *`if [ $# = "2" ] ; then
: empty directory
else
: not empty …
fi
David
UNIX Administratosphere
November 23rd, 2007 at 9:06 pm
David,
It is not working for me. I’m using Debian + Bash 3. It returns 3 when directory is empty, it should be 2 as empty directory has only . and ..
Any idea?
November 23rd, 2007 at 9:29 pm
Yes. I’d forgotten: when no matches are found (”*”) then the resulting text is the character unchanged. This should work better:
FILES=”`echo .* *`”
if [ $FILES = '. .. *' ] ; then
: empty dir
else
: not empty
fi