File count within directories in unix using recursive approach

158 views Asked by At

Problem Statement: To list down the count of files within a directory. Note: A directory may either contain a sub-directory or files but not both. Need to list count of files directory wise. Here is the piece of code.

#!/usr/bin/sh 
directory_navigate()
{   
    path=$1
    cd $path
    dir_count=`ls -l|grep '^d'|wc -l`
    if [ $dir_count -gt 0 ]
    then
        for dir in `ls`
        do
            sub_path="$path/$dir"
            directory_navigate $subpath
        done
    else    
        sub_path=`pwd`
        file_count $sub_path 
        return
    fi
}   

file_count ()
{
    path=$1
    cd $path
    count=`ls|wc -l`
    echo "Count of files in $path is $count"
    return
}

main()
{
    filepath=/var/prod/data/extract/tbill
    directory_navigate $filepath
    return 
}

main 

This throws the following error: recursion too deep

1

There are 1 answers

11
sjsam On

Use globstar . In bash do

shopt -s globstar
count=0
for name in /basefolder/**
do
[ -f "$name" ] && (( count++ ))
done
echo "Total files : $count"

A simpler approach as suggested in the comment is

find /basefolder/ -type f -printfc | wc -c

Here, the catch is that we don't have to parse( and are not parsing, we just want to count) the files, if we require to parse the files for more complex requirements, then below are some reasons for not using find.

  • Using find requires that you need to null-delimit each file (ie use -print0).
  • Furthermore, you need to use while - read -r -d ' ' combination to parse each file.
  • In short, not worth the effort.

Edit: If you want to have a directory-wise file-count listing, do below

#!/bin/bash
shopt -s globstar
for name in ~/Documents/so/**
do
if [ -d "$name" ]
then
  count="$(find "$name" -type f -printf c | wc -c)"
  echo "Total files in $name : $count"
fi
done