Bash Shell Script To Test For Empty Folder

How do I check if a directory contains files? How do I find out if a directory contains files using bash shell under Linux or Unix like operating systems?

To test if folder is empty or not use the following methods.

Method # 1: Find command

The syntax is:

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

You can modify it as follows to work with shell if command:

[ $# -eq 0 ] && { echo "Usage: $0 directory"; exit 2; }
[ ! -d "$dir" ] && { echo "$dir is not a directory."; exit 2; }
if find "$dir" -maxdepth 0 -empty | read;
 echo "$dir empty."
 echo "$dir not empty."

Run the script as follows:
./script /etc
Sample outputs:

/etc not empty.

Create a directory / folder called /tmp/foo using mkdir command:
$ mkdir /tmp/foo
Run the script as follows:
./script /tmp/foo
Sample outputs:

/tmp/foo empty.

Method #2: Other commands

See our previous tutorial and comments for more info:

🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.

🐧 5 comments so far... add one

CategoryList of Unix and Linux commands
Disk space analyzersdf ncdu pydf
File Managementcat cp mkdir tree
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network UtilitiesNetHogs dig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
5 comments… add one
  • Alireza Jul 19, 2012 @ 6:32

    These’re hard ways! You can do it:
    if [ `ls -A “$dir” | wc -l` -eq 0 ]; then echo “Empty!”; fi

  • Saravanan Aug 13, 2012 @ 9:38

    In the find command you need to include the parameter -type d so that it searches only directories and not the files

  • TORNADO Aug 23, 2012 @ 12:41

    if ! ls /path/to/dir/* 2> /dev/null; then echo Empty; fi

  • TORNADO Aug 23, 2012 @ 12:53

    if ! ls /path/to/file/* 2> /dev/null; then
    echo Empty;

  • TORNADO Aug 23, 2012 @ 12:54
    if ! ls /path/to/file/* 2> /dev/null; then
        echo Empty;

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre> for code samples. Still have questions? Post it on our forum