Count files and directories

From raju

Objective

Count the number of files and directories in the current directory.

Solution

Consider the following script

% cat ~/bin/count_files_dirs.sh 
set -- *
files=$#
set -- */
dirs=$#
echo "Number of files in $PWD: $files (including $dirs directories)"

Make it executable

% chmod +x ~/bin/count_files_dirs.sh

Go to the directory of interest and run it

rajulocal@hogwarts ~ % cd ~  
rajulocal@hogwarts ~ % count_files_dirs.sh             
Number of files in /home/rajulocal: 63 (including 55 directories)
rajulocal@hogwarts ~ % cd x 
rajulocal@hogwarts ~/x % count_files_dirs.sh
Number of files in /home/rajulocal/x: 165 (including 6 directories)
rajulocal@hogwarts ~/x % cd ~/bin
rajulocal@hogwarts ~/bin % count_files_dirs.sh
Number of files in /home/rajulocal/bin: 7 (including 1 directories)

Extension

To list the directory names

set -- */; echo $@

Reference and further reading

I found this script in the "Introduction" section of the book "Shell Scripting Recipes - A Problem-Solution Approach" by Chris F. A. Johnson, published in 2005.