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
Use
globstar
. Inbash
doA simpler approach as suggested in the comment is
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.
-print0
).while - read -r -d ' '
combination to parse each file.Edit: If you want to have a directory-wise file-count listing, do below