≡ Menu

Bash Shell Check Whether a Directory is Empty or Not

How do I check whether a directory is empty or not under Linux / UNIX using a shell script? I would like to take some action if directory is empty on a Linux or Unix like system. How can I check from bash/ksh shell script if a directory contains files? How do I check whether a directory is empty or not?

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.
Tutorial details
DifficultyEasy (rss)
Root privilegesNo
RequirementsNone
Estimated completion time2m
In this example, find command will only print file name from /tmp. If there is no output, directory is empty.

Check whether a directory is empty or not using find command

The basic syntax is as follows:

find /dir/name -type -f -exec command {} \;

OR GNU/BSD find command syntax:

find /path/to/dir -maxdepth 0 -empty -exec echo {} is empty. \;

OR

find /path/to/dir -type d -empty -exec command1 arg1 {} \;
In this example, check whether a directory called /tmp/ is empty or not, type:
$ find "/tmp" -type f -exec echo Found file {} \;
Sample outputs:

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"
You can 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
 

Here is another example using bash for loop to check for any *.c files in the ~/projects/ directory:

 
# Bourne/bash for loop example 
for z in ~/projects/*.c; do
        test -f "$z" || continue
        echo "Working on $z C program..."
done
 

Check if folder /data/ is empty or not using bash only features

From the Linux and Unix bash(1) man page:

  • nullglob If set, bash allows patterns which match no files to expand to a null string, rather than themselves.
  • dotglob - If set, bash includes filenames beginning with a . in the results of pathname expansion.
#!/bin/bash
# Set the variable for bash behavior
shopt -s nullglob
shopt -s dotglob
 
# Die if dir name provided on command line
[[ $# -eq 0 ]] && { echo "Usage: $0 dir-name"; exit 1; }
 
# Check for empty files using arrays 
chk_files=(${1}/*)
(( ${#chk_files[*]} )) && echo "Files found in $1 directory." || echo "Directory $1 is empty."
 
# Unset the variable  for bash behavior
shopt -u nullglob
shopt -u dotglob
 

Sample outputs:

$ ./script.sh /tmp
Files found in /tmp directory.
$ mkdir /tmp/foo
$ ./script.sh /tmp/foo
Directory /tmp/foo/ is empty.

A note about ksh user

Try for loop as follows:

 
## In ksh93, prefix ~(N) in front of the pattern
## For example, find out if *.mp4 file exits or not in a dir
cd $HOME/Downloads/music/
for f in ~(N)*.mp4; do
        # do something if file found
        echo "Working on $f..."
done
 
Tweet itFacebook itGoogle+ itPDF itFound an error/typo on this page?

{ 42 comments… add one }

  • David November 23, 2007, 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

  • Raju November 23, 2007, 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?

  • David November 23, 2007, 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

  • Scot January 6, 2009, 1:06 am

    find -type d -empty

    • TJRudd November 2, 2013, 1:30 pm

      `find . -depth -type d -empty` would work a little better..
      EG:

       find . -depth -type d -empty -delete
  • Tomas M May 21, 2009, 12:48 pm

    Thanks Scot!

  • Kyle October 15, 2009, 6:48 pm

    Scot’s suggestion works absolutely perfectly.

  • Indie February 2, 2010, 5:49 pm

    A slight variation on the original post which does it numerically and includes dot files.

    DIR=/home/user
    [ $(( $(ls -a1 $DIR | wc -l) >= 3 )) = 0 ] && echo Empty || echo Nope

    That’s a one and not an ‘l’ to the ls command. An empty directory only has the two entries – . & ..

  • nova May 6, 2010, 5:16 am

    Works with both BSD and GNU Linux find:
    find "/nas/data" -maxdepth 0 -empty -exec echo {} is empty. \;
    OR
    find "/dir2" type d -empty -exec command1 -arg1 {} \;

  • daniel August 9, 2010, 2:50 pm

    I am trying to pass a directory path as a parameter to my bash script (which tests whether its empty), but the directory name contains spaces. Any suggestions?

    • Crístian Viana August 9, 2010, 3:51 pm

      enclose the directory name parameter in double quotes.

      • daniel August 10, 2010, 8:49 am

        The following code does not correctly identify empty directories. Using DIR=$1 then passing “home/dan/not empty” does not help, neither does using “home/dan/not\ empty” or home/dan/not\ empty.

        #!/bin/bash

        DIR=”home/dan/not empty”
        if [ “$(ls -A $DIR)” ]; then
        echo “$DIR is not empty”
        else
        echo “$DIR is empty”
        fi

        • SnakE November 13, 2010, 5:20 am

          Replace

          if [ “$(ls -A $DIR)” ]; then

          with

          if [ “$(ls -A “$DIR”)” ]; then

          That’s just another pair of quotes, no escapes. Should work.

  • pmcneil October 25, 2010, 6:14 am

    dude. give find some love ;-)

    find . -type d -empty -exec touch {}/.empty \;

  • anonymous December 9, 2010, 9:25 pm

    find “/dir2″ -type d -empty -exec command1 -arg1 {} \;

  • kevin January 8, 2011, 1:31 am

    if [ “$(ls -A $DIR)” ]; then
    How can I use this expression exclude one directory?

  • samoak May 4, 2011, 7:40 am

    what if the directory has files but each file is of 0 size?

    best way is to do as below:
    dir_full_path=”/tmp/foo”
    if [ -d “$dir_full_path” ] ; then
    if [ 4 -ge $(du -s “$dir_full_path” ] ; then
    echo “empty directory $dir_full_path”
    else
    echo “non-empty directory $dir_full_path”
    fi
    fi

    This snippet assumes that a directory size, by its own name, is always 4096 bytes, approximated to 4.0K evaluated to int as 4

  • Jairo November 9, 2011, 4:29 am

    Hi all,
    someone please say me why this dont work.

    src=”/Users/xxxx/scripts/dirtest”
    for dir in `ls -R “$src”`
    do
    if [ -d “$dir” ]; then
    echo this is a dir: $dir
    fi
    done

    thanks

    • ReddyRace December 9, 2011, 9:58 pm

      Jairo :

      Declare the variable ,before you use it.

  • stainless January 5, 2012, 3:09 pm

    Ok, this works, after hours of coding a simple solution was found to be best loll.What kept giving me trouble was the *, also I had found a solution a long time ago, but it didnt work if you had empty files in the directory.I tried all the IF statement solutions and it wont work in all situations.So best method is below:

    #!/bin/bash

    DIR=/var/www/tee

    for i in $DIR/*
    do
    if [ -e $i ] && [ $(echo $?) -eq “0 ” ]

    then
    echo The Directory is NOT EMPTY

    else

    echo The directory is EMPTY

    fi
    done

  • Vijay Kanta September 12, 2012, 5:58 am

    Very good Vivek. Cool.

  • DejanLupo September 13, 2012, 10:46 am

    if [ $( stat -c %h . ) -gt 2 ] ; then echo not empty; fi
    Solution with “$(ls -A $DIR)” could exceed command buffer size.

  • plums September 18, 2012, 8:35 am

    Square brackets are only needed with if when you’re using test expressions, and by doing away with them you can do away with the process substitution. You can test the exit status of a program or command just by running it. (Getting ls to give an error code in this case requires a slight change in syntax.)

    if ! ls -A $DIR/* > /dev/null 2>&1; then
        echo "Take action $DIR is not Empty"
    else
        echo "$DIR is Empty"
    fi
    

    alternately,

    if ls -A $DIR/* > /dev/null 2>&1; then
        echo "$DIR is Empty"
    else
        echo "Take action $DIR is not Empty"
    fi
    
  • Gibarian September 26, 2012, 12:44 pm

    If used in a script, I’d go with a slight modification of the first comment (as the “set” clobbers positional parameters, putting it in a function will clobber only local function parameters, not the global ones!):

    shopt -s dotglob nullglob
    is_empty_dir() {
      set - "`echo $1/*`"
      test -z "$1"
    }
    

    And then calling:

      is_empty_dir 
  • neuralys November 14, 2012, 12:46 pm

    why not using simple :

    if [ ! -f /folder/* ]; then
    echo “folder not empty”
    else
    echo “folder empty”
    fi

  • ThePowerTool February 15, 2013, 3:05 pm

    I had a seriously nasty time with this.

    In a bash script I wanted to:
    1. Create and pass a list of directories that match a pattern
    2. Use a variable to check if the directories matching the pattern were empty
    3. Delete empty directories.

    The challenge I ran into was with wildcard expansion in variables. I spent a little while pulling my hair out over ” and ‘ and ` until I figured out (the final solution was pretty simple).

    Here is my short script that
    1. creates a list of directories within $1 that match a pattern
    – in this case the grep returns all directories that are 5 numerical digits
    2. verifies whether or not content exists
    3. deletes the directory if no content is present

    #!/bin/bash
    # List Empty Directories that are directories in the
    # format ./##### If they are empty, delete them.

    ls -d */ > testdir.txt
    grep ‘[0-9]\{5\}’ ./testdir.txt > testdir2.txt
    rm ./testdir.txt

    i=1

    while [ $i -le `wc -l ./testdir2.txt | gawk ‘{print $1}’` ]; do
    line=`head -$i ./testdir2.txt | tail -1`
    correctdirname=”./”$line
    echo -n “Dir “$i” “$correctdirname

    files=`echo $correctdirname $correctdirname*`
    test=$correctdirname” “$correctdirname”*”
    if [ “$files” == “$test” ]
    then echo ” empty” #; rm -rf $correctdirname
    else echo ” files found”
    fi

    i=`expr $i + 1`

    done

    For safety I commented out the delete/rm. Anyone trying this should test carefully before running this script and use a test directory with test data. The delete command will delete entire directories whether they are empty or not! Verify your scenario, verify the variables match your scenario, and double-check before uncommenting that rm command.

    I hope someone finds this useful.

  • ThePowerTool February 15, 2013, 3:11 pm

    Minor correction:

    I mistakenly said “1. creates a list of directories within $1 that match a pattern”
    It should read “1. creates a list of directories within the current directory that match a pattern”

    Also I didn’t remove testdir2.txt, created by the script in the current directory. A line to remove that could be added after the “done” to clean up the 2nd temporary file created by the script.

  • ThePowerTool February 15, 2013, 3:25 pm

    After having solved the logic problem I was overly-focused on I was playing around with additional information from the above posts and changed my if statment based upon the one provided by nixcraft, above:
    My if original: if [ “$files” == “$test” ]
    Nixcraft’s if: if [ “$(ls -A $DIR)” ]
    My new if: if [ ! “$(ls -A $line)” ]

    Using the if provided by Nixcraft I came up with an if that works in place of the if statement in my above script and is a little cleaner because it does not require creation of the $test variable. I put a ! in front of it so I could easily swap if statements. Alternately you could reverse the then-else.

    Here is the updated script with the old vars and if commented out:

    #!/bin/bash
    # List Empty Directories that are directories in the
    # format ./##### If they are empty, delete them.

    ls -d */ > testdir.txt
    grep ‘[0-9]\{5\}’ ./testdir.txt > testdir2.txt
    rm ./testdir.txt

    i=1

    while [ $i -le `wc -l ./testdir2.txt | gawk ‘{print $1}’` ]; do
    line=`head -$i ./testdir2.txt | tail -1`
    correctdirname=”./”$line
    echo -n “Dir “$i” “$correctdirname

    # files=`echo $correctdirname $correctdirname*`
    # test=$correctdirname” “$correctdirname”*”
    # if [ “$files” == “$test” ]
    if [ ! “$(ls -A $line)” ]
    then echo ” empty” #; rm -rf $correctdirname
    else echo ” files found”
    fi

    i=`expr $i + 1`

    done

    rm ./testdir2.txt

    Note I added the final line to remove the 2nd test/data file.

    Also you should be able to comment out the if and uncomment the 3 lines above it to switch back and forth between the two options.

  • ThePowerTool February 15, 2013, 3:43 pm

    This is why I don’t post often. I keep finding mistakes. I don’t know how other posters do it–such simple elegant posts that are correct.

    Upon further inspection I realized my if statement, while it works in my bash, is using the wrong variable. I created the $correctdirname variable because grepping directories gave me ##### rather than ./#####.
    if [ ! “$(ls -A $line)” ]

    I believe you should be using $correctdirname for the reason above even though the script works for me–I don’t know if it will work generically given the difference.

    The “more-correct” if-statement:
    if [ ! “$(ls -A $correctdirname)” ]

  • TheOne May 24, 2013, 9:07 pm

    if [ ! “$(ls -A “$FOLDER”)” ]; then
    echo “$FOLDER is empty”
    fi

  • Jonathan D. Lettvin June 26, 2013, 6:57 pm

    When searching for methods to automatically mount virtualbox shared folders,
    reliable and correct methods are hard to distinguish from those that fail.
    Failures include getting and setting permissions, as well as other problems.

    Methods that fail include:
    modifying /etc/fstab
    modifying /etc/rc.local

    I am fairly certain that rc.local can be used,
    but no methods I have tried worked.
    I welcome improvements on these guidelines.

    On virtualbox 4.2.14 running nautilus (bash terminal) on an ubuntu 13.04 guest,
    Below is a working method to mount Common (sharename)
    on /home/$USER/Desktop/Common (mountpoint) with full permissions.
    (Note the ‘\’ command continuation character in the find command.)

    First time only: create your mountpoint, modify your .bashrc file, and run it.
    Respond with password when requested.
    These are the four command-lines needed.

    mkdir $HOME/Desktop/Common
    sudo echo “$USER ALL=(ALL) NOPASSWD:ALL” >> /etc/sudoers
    find $HOME/Desktop/Common -maxdepth 0 -type d -empty -exec sudo \
    mount -t vboxsf -o \
    uid=`id -u $USER`,gid=`id -g $USER` Common $HOME/Desktop/Common \;
    source ~/.bashrc # Needed if you want to mount Common in this bash.

    All other times: simply launch a bash shell.

    The find command detects an empty mountpoint directory.
    If the Common directory is not empty, it does not run the mount command.

    I hope this is error-free and sufficiently general.
    Please let me know of corrections and improvements.

  • Janani August 4, 2013, 5:58 am

    How to make two directories “C_ Programming ” and “Shell Script” ?

  • Janani August 4, 2013, 6:01 am

    A)Create a text file “Pros_and_Cons_of_C.txt” in “C_programming” directory
    B)Create a text file “Pros_and_Cons_of_C.txt” in “Shell_Script” directory
    C)Write a suitable pros and cons for each text file in your own words using keyboards inputs.

  • Janani August 4, 2013, 6:06 am

    Write a shell script to create a directory “Shell2″ Create 10 text files “a5_1.txt” “a5_10.txt” using loop inside the directory “Shell2.” Give access privilege for those text files , read only for others and group , read and write for owner..

    Please help me for above all forums that i sent. those are may be primary level questions , but i can’t understand for answer those questions. please help me for do my university assignment..

    Thank you

  • Philippe Petrinko August 6, 2013, 9:17 am

    @Janani:

    That’s great for you, learning Linux computer science, and this means first: learn. Nobody can do it for you.
    Fortunately, somebody has built and offered to all a great resource to learn, which is also a cooperative work:
    http://bash.cyberciti.biz/guide/Main_Page

    Enjoy!

  • Philippe Petrinko August 6, 2013, 9:20 am

    @Janani:

    I could have added, among other resources:

    http://www.cyberciti.biz/tips/linux-unix-commands-cheat-sheets.html

    Enjoy++ !

  • Erik Lundmark October 5, 2013, 2:49 pm

    Not a better solution, but this also works:

    [[ `du $FOLDER` =~ ^4[^0-9] ]] && echo "is empty"
  • Erik Lundmark October 5, 2013, 2:55 pm

    Please remove/disregard my previous comment, this is what I meant. Checks for just one folder (current one) and it’s size being 4096 bytes.

    [[ `du -ab $PWD` =~ ^4096[^0-9]+.$ ]] && echo "is empty"
  • Me June 6, 2014, 5:13 am

    #!/bin/bash

    rm -rf “%*”
    mkdir “%*”
    echo NOW it’s empty.
    exit 0

  • Chris August 26, 2014, 3:08 pm

    Thanks for this post! I have a comment and a potential method.

    Method: Why wouldn’t this work?
    ls $DIR/*
    echo $? # a ‘1’ would mean the directory is empty

    Comment: As far as I can tell, this version, the find command version, and ls -A, will not detect a directory that contains subdirectories but is void of files. I am perplexed that the below does not work. Assume $DIR has a single subdirectory, foo, and neither have regular files:
    find $DIR -type f -exec echo $DIR is empty \;

    Thanks!

  • Chris August 26, 2014, 3:25 pm

    PS I did find for my ancillary problem (may contain subdirectories but no files) this solution:
    let “$m = `find $DIR -type f | wc -l`” ; test $m = 0 ; echo $?

    Also, a nit in my original suggestion: adjust the ls command so you don’t get unwanted output:
    ls $DIR/* > /dev/null
    echo $? # a ’1′ would mean the directory is empty

  • Ronald January 23, 2015, 12:54 pm

    The example

    if [ “$(ls -A $DIR)” ]; then
    echo “Take action $DIR is not Empty”
    else
    echo “$DIR is Empty”
    fi

    could be written a bit simpler without backquote substitution:

    if ls -A $DIR >/dev/null
    then
    echo Take action ….
    else
    echo $Dir is empty
    fi

Leave a Comment