Shell script that counts the number of files with a specific permission

Shell Scripting @ Freshers.in

Shell scripting offers a powerful means of automating file management and analysis tasks, enabling users to efficiently manipulate and inspect files within a directory. In this article, we’ll explore the development of a shell script that accepts a directory name as an argument and displays the number of files within that directory possessing a specific permission. We’ll delve into the script’s implementation, provide illustrative examples, and showcase the output to demonstrate its effectiveness in file analysis and inspection.

Understanding the Shell Script:

The shell script we’ll be creating will utilize Unix commands and shell scripting constructs to traverse the specified directory, identify files with the specified permission, and count the occurrences.

Script Implementation:

#!/bin/bash
# Check if directory name and permission argument are provided
if [ $# -ne 2 ]; then
    echo "Usage: $0 <directory> <permission>"
    exit 1
fi
# Assign directory name and permission to variables
directory="$1"
permission="$2"
# Check if the specified directory exists
if [ ! -d "$directory" ]; then
    echo "Error: Directory '$directory' not found."
    exit 1
fi
# Count files with the specified permission
count=$(find "$directory" -type f -perm "$permission" | wc -l)
echo "Number of files with permission '$permission' in '$directory': $count"

Example Usage:

Suppose we have a directory named “documents” containing various files with different permissions. We’ll execute the shell script with the directory name and a specific permission as arguments to count the number of files possessing that permission.

$ ./count_files_with_permission.sh documents 644

Output:

Upon execution of the script, the number of files within the specified directory possessing the specified permission will be displayed.

Number of files with permission '644' in 'documents': 7
Author: user