Programming In Shell Script: Count Files

Here is a sample shell script program that simply counts the number of regular files, directories and symbolic links within a directory, but excludes counting items within subdirectories.


# The script accepts a directory and produces output that tells how many regular files, directories, and symbolic links are in the directory (exclude subdirectories).
# The words in the output are singular or plural depending on the count (e.g. 1 link, 2 links).  Make sure the directory exists.
# Use the current directory if none was provided.
# Print out a "Usage" message if the user gave more than one argument.

# Syntax:   countfiles.sh directory

#!/bin/bash

#usage
directory=$1
[ $# -eq 0 ] && directory=$PWD
[ $# -gt 1 ] && { echo "Usage: countfiles.sh requires one directory as a parameter."; exit 1; }

dirs=0;files=0;links=0
# take directory parameter and check if it exists
# $0 is the directory
[ -d $directory ] || { echo "Directory specified either does not exist or is of a different file type."; exit 1; }

# loop through files in directory
for file in $directory/*;
do
	[ -d "$file" ] && dirs=`expr $dirs + 1`
	[ -f "$file" ] && files=`expr $files + 1`
	[ -h "$file" ] && links=`expr $links + 1`
done

echo "Directory $directory contains:";
if [ $dirs -eq 1 ]; then
	echo "$dirs directory"
else
	echo "$dirs directories"
fi
if [ $files -eq 1 ]; then
	echo "$files file"
else
	echo "$files files"
fi
if [ $links -eq 1 ]; then
	echo "$links symbolic link"
else
	echo "$links symbolic links"
fi

exit 0

Here is a test:

jordan@jordan-VirtualBox:~/Desktop$ mkdir testDir
jordan@jordan-VirtualBox:~/Desktop$ cd testDir
jordan@jordan-VirtualBox:~/Desktop/testDir$ touch regular_file
jordan@jordan-VirtualBox:~/Desktop/testDir$ mkdir directory
jordan@jordan-VirtualBox:~/Desktop/testDir$ ln -s ~/Desktop/testDir/regular_file symbolic_link
jordan@jordan-VirtualBox:~/Desktop/testDir$ ls -l
total 4
drwxr-xr-x 2 jordan jordan 4096 2011-12-14 11:10 directory
-rw-r--r-- 1 jordan jordan    0 2011-12-14 11:10 regular_file
lrwxrwxrwx 1 jordan jordan   41 2011-12-14 11:11 symbolic_link -> /home/jordan/Desktop/testDir/regular_file
jordan@jordan-VirtualBox:~/Desktop/testDir$ cd ../
jordan@jordan-VirtualBox:~/Desktop$ ./countfiles.sh testDir
Directory testDir contains:
1 directory
2 files
1 symbolic link

After creating our test folder, the outputs of count files performs well. Even though a link is different than a regular file, it is still a file all the same, so we have a count of 2 files in our report.

Extremely simple but extremely useful to have as a nice command line tool. Make an alias for it in your Linux environment and simply run “countfiles.sh”. If the directory argument is blank, it will use the current directory.

Download: countfiles.zip

Comments are closed.