Writing a Shell Script to Count Files in the Current Directory

Shell Scripting @ Freshers.in

Efficiently managing files within a directory is a fundamental task for developers, system administrators, and anyone working in a command-line environment. Counting the number of files in a directory can be a useful skill for various purposes, such as monitoring directory contents or generating statistics. In this article, we will guide you through the process of writing a Shell script to count the number of files in the current directory. We’ll provide step-by-step examples and the expected output to help you become proficient in this essential directory operation.

Prerequisites:

Before we delve into writing the Shell script, ensure you have the following prerequisites in place:

  1. A Unix-like operating system with a shell environment (e.g., Bash).
  2. Basic knowledge of using the command line.

Writing the Shell Script:

Let’s create a Shell script that counts the number of files in the current directory. We will use common Unix shell commands, such as ls and wc.

#!/bin/bash

# Get the list of files in the current directory and count them
file_count=$(ls -l | grep -v '^d' | wc -l)

# Print the total number of files in the current directory
echo "Total number of files in the current directory: $file_count"

Explanation:

  • We start the script with the shebang #!/bin/bash, indicating that it should be interpreted using the Bash shell.
  • ls -l is used to list the contents of the current directory in long format, including details about files and directories.
  • grep -v '^d' is used to exclude lines that start with ‘d’, which are directories. This ensures that we only count files.
  • wc -l counts the number of lines in the output of ls -l, which corresponds to the number of files.
  • The result is stored in the variable file_count.
  • Finally, we use echo to print the total number of files in the current directory.

Executing the Script:

To execute the script, follow these steps:

  1. Save the Shell script to a file with a .sh extension (e.g., count_files.sh).
  2. Open your terminal or command prompt and navigate to the directory where you want to count files.
  3. Make the script executable by running the command:
chmod +x count_files.sh

Run the script by executing:

./count_files.sh

Output:

Upon running the script, you will see an output message displaying the total number of files in the current directory. For example:

Total number of files in the current directory: 15
Author: user