Shell Script to list the Number of Entries Present in Each Subdirectory Mentioned in the Path
Last Updated :
17 Oct, 2022
In this article, we will discuss how to write a shell script to list the Number of Entries Present in Each Subdirectory Mentioned in the Path
Examples:
Directory: GeeksforGeeks
Subdirectories: GeeksforGeeks/Subdirectory1, GeeksforGeeks/Subdirectory2
Entries in Subdirectory1: gfg.txt, temp.sh
Entries in Subdirectory2: foo.txt, script.sh, pro.exe
Output: ./ Subdirectory1: 2
./ Subdirectory2: 3
Script:
# Shell script to count number of entries
# present in subdirectories of a path
# !/bin/sh
find . -maxdepth 1 -type d | while read -r dir
do printf “%s:\t” “$dir”; find “$dir” -type f | wc -l; done
Output:
Explanation:
Each of the lines of this script has been explained below in detail:
- find . -maxdepth 1 -type d: This statement returns a list of all subdirectories present in the current path or directory.
- while read -r dir; do: This statement initiates a while loop as long as the pipe that comes to the while is open.
- printf “%s:\t” “$dir”: This statement will print the string in $dir (that holds one of the directory names) that is followed by a colon and a tab space.
- find “$dir” -type f: Makes the list of all the entries that inside the directory which is held by $dir:
- wc -l: This statement is used to count the number of lines that are passed to the input.
- done: This statement will terminate the while loop.
Share your thoughts in the comments
Please Login to comment...