Bash Scripting: Counting File and Directory Numbers in a Root Path Parameter
Bash scripting is an essential skill for any system administrator or developer working in a Unix-like environment. One common task when working with the command line is counting the number of files and directories in a given path. In this article, we will explore how to write a Bash script to list all the folders in a root path and count the number of files in each one.
Prerequisites
Before we begin, it is assumed that the reader has a basic understanding of the Bash shell and how to navigate the file system using the command line. Familiarity with command line utilities such as ls, cd, and find is also recommended.
The Script
The following script, which we will call count_files.sh, takes a root path as a parameter and lists all the folders in that path, along with the number of files in each one:
Let's break down how this script works:
#!/bin/bash: This line, known as the shebang, tells the system that this script should be executed using the Bash shell.if [ -z "$1" ]; then ... fi: This block checks if a root path was provided as an argument to the script. If not, it prints an error message and exits with a non-zero status code.ROOT_PATH="$1": This line sets the root path to the provided argument.FOLDERS=$(find "$ROOT_PATH" -type d): This line uses thefindcommand to list all the folders in the root path. The output is stored in theFOLDERSvariable.for FOLDER in $FOLDERS; do ... done: This block loops through each folder in theFOLDERSvariable and counts the number of files in each one.echo "Folder: $FOLDER": This line prints the name of the current folder.echo "Files: $(find "$FOLDER" -type f | wc -l): This line uses thefindcommand to list all the files in the current folder, pipes the output to thewccommand to count the number of lines, and prints the result.
Usage
To use the script, simply provide a root path as an argument:
```bash $ ./count_files.sh /path/to/root ```This will list all the folders in the /path/to/root directory, along with the number of files in each one.
In this article, we have explored how to write a Bash script to list all the folders in a root path and count the number of files in each one. This is just one example of the many powerful tasks that can be accomplished using Bash scripting. With practice and experience, you can harness the full potential of the Bash shell to automate complex tasks and streamline your workflow.