Shell script that removes all files with a specific extension in a directory

Shell Scripting @ Freshers.in

In the realm of shell scripting, automating file management tasks is essential for streamlining workflows and optimizing productivity. In this article, we’ll delve into the creation of a shell script that takes a directory name as an argument and removes all files with a specific extension within that directory. We’ll provide detailed insights into the script’s implementation, accompanied by examples and outputs to illustrate its functionality and efficacy in file management operations.

Understanding the Shell Script:

The shell script we’ll be developing will leverage Unix commands and shell scripting constructs to traverse the specified directory, identify files with the specified extension, and remove them from the filesystem.

Script Implementation:

#!/bin/bash
# Check if directory name argument is provided
if [ $# -ne 2 ]; then
    echo "Usage: $0 <directory> <extension>"
    exit 1
fi
# Assign directory name and extension to variables
directory="$1"
extension="$2"
# Check if the specified directory exists
if [ ! -d "$directory" ]; then
    echo "Error: Directory '$directory' not found."
    exit 1
fi
# Remove files with the specified extension
find "$directory" -type f -name "*.$extension" -exec rm -f {} \;
echo "Files with extension '$extension' removed from '$directory'."

Example :

Let’s assume we have a directory named “documents” containing files with the “.tmp” extension. We’ll execute the shell script with the directory name and extension as arguments to remove all files with the specified extension.

$ ./remove_files_by_extension.sh documents tmp

Output:

Upon execution of the script, all files with the specified extension within the specified directory will be removed, and a confirmation message will be displayed.

Files with extension 'tmp' removed from 'documents'.
Author: user