Learn how to create a script to count subdirectories within a specified directory using Shell scripting

Shell Scripting @ Freshers.in

Before diving into the scripting details, it’s essential to understand what we aim to accomplish. We want to create a script that accepts a directory name as an argument and outputs the total number of subdirectories within it. This script will be particularly useful for system administrators and developers who often need to assess directory structures quickly.

Step-by-Step Guide

Creating the Script

Open your preferred text editor and create a new file named count_subdirs.sh. This file will contain our script.

The Script Content

Copy and paste the following shell script into your new file:

#!/bin/bash
# Check if a directory name is provided as an argument
if [ "$#" -ne 1 ]; then
    echo "Usage: $0 <directory_name>"
    exit 1
fi
# Assign the directory name to a variable
DIR=$1
# Check if the provided argument is indeed a directory
if [ ! -d "$DIR" ]; then
    echo "Error: $DIR is not a directory."
    exit 1
fi
# Count the number of subdirectories
SUBDIR_COUNT=$(find "$DIR" -type d -mindepth 1 | wc -l)
# Output the result
echo "The total number of subdirectories in '$DIR' is: $SUBDIR_COUNT"

Save and close the file.

Making the Script Executable

Run the following command in your shell to make the script executable:

chmod +x count_subdirs.sh

Running the Script

To execute the script, use the following command:

./count_subdirs.sh /freshers/src/viewcnt

Testing the Script

For testing purposes, let’s create a sample directory structure:

mkdir -p test_directory/{subdir1,subdir2,subdir3/{nested1,nested2}}

This command will create a directory named test_directory with two subdirectories and an additional subdirectory subdir3 containing two nested subdirectories.

Now run the script with the newly created test_directory as an argument:

./count_subdirs.sh test_directory

The output should be:

The total number of subdirectories in 'test_directory' is: 5

Read more on Shell and Linux related articles

Other urls to refer

  1. PySpark Blogs
Author: user