Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursively count specific files BASH

My goal is to write a script to recursively search through the current working directory and the sub dirctories and print out a count of the number of ordinary files, a count of the directories, count of block special files, count of character special files,count of FIFOs, and a count of symbolic links. I have to use condition tests with [[ ]]. Problem is I am not quite sure how to even start.

I tried the something like the following to search for all ordinary files but I'm not sure how recursion exactly works in BASH scripting:

function searchFiles(){
    if [[ -f /* ]]; then
        return 1
    fi
}
searchFiles
echo "Number of ordinary files $?"

but I get 0 as a result. Anyone help on this?

like image 583
jamesy Avatar asked Jun 07 '11 16:06

jamesy


People also ask

How do I count files in a directory in bash?

To determine how many files there are in the current directory, put in ls -1 | wc -l. This uses wc to do a count of the number of lines (-l) in the output of ls -1.

How do I count files in a folder and subfolders?

To count all the files and directories in the current directory and subdirectories, type dir *. * /s at the prompt.


2 Answers

Why would you not use find?

$ # Files
$ find . -type f | wc -l
327
$ # Directories
$ find . -type d | wc -l
64
$ # Block special
$ find . -type b | wc -l
0
$ # Character special
$ find . -type c | wc -l
0
$ # named pipe
$ find . -type p | wc -l
0
$ # symlink
$ find . -type l | wc -l
0
like image 113
MattH Avatar answered Nov 05 '22 10:11

MattH


Something to get you started:

#!/bin/bash

directory=0
file=0
total=0

for a in *
do
   if test -d $a; then
      directory=$(($directory+1))
   else
      file=$(($file+1))
   fi

   total=$(($total+1))
   echo $a

done

echo Total directories: $directory
echo Total files: $file
echo Total: $total

No recursion here though, for that you could resort to ls -lR or similar; but then again if you are to use an external program you should resort to using find, that's what it's designed to do.

like image 29
Fredrik Pihl Avatar answered Nov 05 '22 09:11

Fredrik Pihl