Recursively count specific files BASH

jamesy picture jamesy · Jun 7, 2011 · Viewed 10.3k times · Source

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?

Answer

MattH picture MattH · Jun 7, 2011

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