Open In App

Shell Script to Delete the Zero Sized File Using If and For

Improve
Improve
Like Article
Like
Save
Share
Report

There are many files in our system which are of no use for us as temporary files. So we need to clear all those files, but it is very hectic to find each file and delete them. Here we will create a script that will automatically search for the zero-sized file and delete them all.

Before starting, we will see how to search for directories.

Searching current directory to list the directories whose name starts with uppercase.

# find . -type d -name "[A-Z]*" -ls

The approach of the code:

  • Create a terminal user interface which will ask for the directory name from which the empty files will be deleted.
  • Then check if the input directory exists or not using file operators like “-d” explained in the code.
  • Then use a method to search the given directory for the zero-sized file. We will here use the above explained “find” command to do the same.
  • As we now have the list of all the zero-sized files, we could delete them by using for loop. And hence we have achieved our goal.

Below is the implementation:

#!/bin/bash
echo "Enter the Directory for which all the zero sized files will be deleted:"

# input directory name.
read dirName
echo "For $dirName all 0 Sized files will be deleted."

# variable to store all the zero size files name.
# to store command output in variable we have two syntax 1. var=$(command) 2. var='command'

dire = $(find . -type f -size 0)

# first check if directory exist.
# -d is the file test operator which check the directory if it exits or not.Return true for existing.
if [ ! -d $dirName ];

then
echo "This is an invalid directory name or the Name directory does not exist."
else

# for loop iterate on the filenames with zero size.
for fileName in $dire
do

# to remove a file whose name starts with "-" we use option "--".
rm -- $fileName
done
fi

Create some empty files in your directory using the touch command. Touch command takes a filename as an argument.

# touch file1.txt file2.txt file3.txt

Give permission to make the script executable.

# chmod 777 deleteFile.sh

Run the script now and give the directory name, here we are using the current directory (.).

#  ./deleteFile.sh


Last Updated : 22 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads