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
Featured Articles:
- 20 Linux System Monitoring Tools Every SysAdmin Should Know
- My 10 UNIX Command Line Mistakes
- 10 Greatest Open Source Software Of 2009
- Top 5 Email Client For Linux, Mac OS X, and Windows Users
- Top 20 OpenSSH Server Best Security Practices
- Top 10 Open Source Web-Based Project Management Software
- Top 5 Linux Video Editor Software
- Email FAQ to a friend
- Download PDF version
- Printable version
- Comment RSS feed
- Last Updated: 11/22/07



{ 7 comments… read them below or add one }
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
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?
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
find -type d -emptyThanks Scot!
Scot’s suggestion works absolutely perfectly.
A slight variation on the original post which does it numerically and includes dot files.
That’s a one and not an ‘l’ to the ls command. An empty directory only has the two entries – . & ..