How to count number of files and subdirectories with shellscript? How to count number of files and subdirectories with shellscript? shell shell

How to count number of files and subdirectories with shellscript?


How about using a find like this:

Files="$(find . -type f -maxdepth 1 -printf x | wc -c)"Directories="$(find . -type d -maxdepth 1 -printf x | wc -c)"

The Directories will also include the root directory (.)


I suggest two changes: eliminate the unnecessary files variable, and use a glob instead of parsing the output of ls. Then use the -d test to see if each directory entry is a directory (if it's not, assume it's a regular file, unless you really care about distinguishing named pipes, character devices, block devices, etc) and use the $((...)) expression for arithmetic.

echo "What absolute directory do you want to count?"read DIRcd "$DIR" || exitfile=0dir=0for d in *;do    if [ -d "$d" ]; then        dir=$((dir+1))    else        file=$((file+1))    fidoneecho "Files $file"echo "Directories $dir"


This can be done exactly in 3 lines:

read -p " Please enter the directory you want to count its files & subdirectories = " pathecho "Number of directories in $path =  "$(find $path/* -type d | wc -l)echo "Number of Files in $path = "$(find $path/* -type f | wc -l)