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:

#!/bin/bash
dir=$1
 
[ $# -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;
then
 echo "$dir empty."
else
 echo "$dir not empty."
fi

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:

Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.