Shell Script – Check Empty Folder

I am working on a housekeeping shell script to delete old files and update some files. I want to know whether the .sh is completed without problem. So i made a checking part in the shell script.

The following .sh example checks if a folder is empty or not.

# Read a folder path from user input and check if it is
# empty or not

# Read the folder location
# "\c" means keep the cursor on the same line
echo "Please input the folder location: \c"
read _folder

# Quit if the folder does not exist
if [ ! -e $_folder ]; then
        echo 'Sorry, folder does not exist.'
        exit 1

# Check if the folder is empty or not
if [ $(ls $_folder | wc -l) -eq 0 ]; then
        echo "$_folder is EMPTY"
        echo "$_folder is NOT EMPTY"

Done =)

2 thoughts on “Shell Script – Check Empty Folder”

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

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

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


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.