8

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?

jamesy
  • 81
  • 1
  • 1
  • 2
  • where us the recursive call? and why recursion. Note that you would be able to only return a max value of 255 as the return value is limited by 1 byte (8 bit byte). – phoxis Jun 07 '11 at 17:01
  • have a look at `pushd` and `popd` – phoxis Jun 07 '11 at 17:05

2 Answers2

42

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
MattH
  • 37,273
  • 11
  • 82
  • 84
3

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.

Fredrik Pihl
  • 44,604
  • 7
  • 83
  • 130
  • 1
    instead of `*` use `**` for recursion. `shopt globstar` has to be *on* for this to work. (`shopt -s globstar` to enable) – kon Jun 07 '11 at 23:54