How to separately count number of files, directories, symbolic links and hard links within a single find run

findhardlinkmigrationsymbolic-link

To check a successfull migration I'm using find to count the number of files, directories, symbolic links and files with more than one hard link. As the directories to check contain a huge number of files, each find run takes several hours. Thus I search for a way to separately count number of files, directories, symbolic links and files with more than one hard link within a single find run.

Here's what I currently do

num_files=$(find $directory -type f | wc -l)
num_directories=$(find $directory -type d | wc -l)
num_symlinks=$(find $directory -type l | wc -l)
num_hardlinks=$(find $directory -type f -links +1 | wc -l)

How can I get those four counters within one find run?

Best Answer

The following should do it. It requires GNU find; on OS X, install e.g. findutil using Homebrew.

find $directory -type d -printf d -o -type l -printf l -o -type f -links +1 -printf h -o -type f -printf f

This will print one character per encountered file system entry:

  • d if it's a file
  • l if it's a symbolic link
  • h if it's a file with hard links
  • f if it's a file (only if not h)

Output looks like this (actual excerpt on my system):

dfddfdfddfdfddfdfddfdfddfdfddfddfdfddfdffffffffddfdffdfffffffffddfdldfllfdlldffffdfllfdlllllldffffdffffldfllfddffdldfddddffffflllldllllldlffffldfllfdlldffffdfllfddffddfddddfffffldfddddfffffdfddddfffffdlllldffffldfffflflllldffflfdffflfdfllfddffffldffffdfffflldfffflllldffffdffffdfffflldfllfddffdldfddddfffffdllllddflfffflldfllfddffffdffffdffffldffffdffffdffffdffffllldffffldffffdffffldffffldffffdffffdffffllllllldffffldffffdfffflllllldfffflldffddldfllfdldfffflldfffflldffffdfffflldffffdffffdfllfdlldfffflllldfllfdlldffffdfllfdlllllldffffdffdldfllfdlldfffflldfffflldffffldffffldfffflldfllfdldffffldffffldffdldffdddffddffddffddldfllfdlldffffdffffdfffflldfffflldffffdffffllldffffdffffdfllfddffffldfffflllldffffldfffflllldffffdfllfddffdldddddfffdddddfffdddddfffdddddfffdldlfffflldlffffllldfffllldffffdlffffdlffffldfffflldffdldfllfdllldffffdffffdffffldfllfdlllldfffflldfllfdldfddffffffl

Redirect output to a file, and then it becomes simple string processing to count later.

Related Question