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.

#!/bin/sh
# 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
fi

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

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:
    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

    Like

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s