In this article, we will learn how to create a shell script that finds and lists all empty files in a specified directory. Empty files can sometimes clutter directories, and identifying them can be useful for cleanup or auditing purposes. We will guide you through writing a simple yet effective script in bash that performs this task efficiently.
Table of Contents
Prerequisites
- AWS Account with Ubuntu 24.04 LTS EC2 Instance.
- Basic knowledge of Shell scripting.
Step #1:Create the Script File
First, we need to create a new shell script file. Open your terminal and run the following command to create a file named empty_files.sh
nano empty_file.sh

Step #2:Write the Script to find and list empty files
Add the following code to the file.
#!/bin/bash
# Get the directory from the first script argument
directory="$1"
# Check if the directory argument is provided
if [ -z "$directory" ]; then
echo "Usage: $0 <directory>"
exit 1
fi
# Check if the provided argument is a valid directory
if [ ! -d "$directory" ]; then
echo "Error: '$directory' is not a valid directory."
exit 1
fi
# Find and list all empty files in the directory
echo "Empty files in $directory:"
find "$directory" -type f -empty

Explanation of the Script:
- Shebang Line:
#!/bin/bash
specifies the script should be run with the bash shell. - Directory Argument: directory=”$1″ captures the first argument passed to the script as the directory to search.
- Argument Check: if [ -z “$directory” ]; checks if the directory argument is empty and prompts the user with the correct usage if true.
- Directory Validity Check: if [ ! -d “$directory” ]; checks if the provided argument is a valid directory.
- Find Command: find “$directory” -type f -empty searches for empty files (-type f) in the specified directory (-empty).
Step #3:Make the Script Executable
Make the script executable by changing its permissions.
chmod +x empty_file.sh

Step #4:Run the Script
To run the script, use the following command in the terminal, We need to provide a directory as an argument when running the script.
sudo ./empty_file.sh /var/log

This will display all the empty files from the /var/log directory.
Conclusion:
In conclusion, creating a shell script to find and list empty files in a directory is a straightforward task that can greatly assist in managing and maintaining clean directories. This script checks for the validity of the input directory, utilizes the powerful find
command to locate empty files, and provides a user-friendly output. By following the steps outlined in this article, you can easily create and use this script to streamline your file management tasks.
Related Articles:
Shell Script to send email if website down
Reference: