Created
September 2, 2014 13:44
-
-
Save lazyval/d6f18a0d188b70a70a00 to your computer and use it in GitHub Desktop.
Utility that can be used to count files in a given directory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
countFiles () { | |
# call the recursive function, throw away stdout and send stderr to stdout | |
# then sort numerically | |
countFiles_rec "$1" 2>&1 >/dev/null | sort -nr | |
} | |
countFiles_rec () { | |
local -i nfiles | |
dir="$1" | |
# count the number of files in this directory only | |
nfiles=$(find "$dir" -mindepth 1 -maxdepth 1 -type f -print | wc -l) | |
# loop over the subdirectories of this directory | |
while IFS= read -r subdir; do | |
# invoke the recursive function for each one | |
# save the output in the positional parameters | |
set -- $(countFiles_rec "$subdir") | |
# accumulate the number of files found under the subdirectory | |
(( nfiles += $1 )) | |
done < <(find "$dir" -mindepth 1 -maxdepth 1 -type d -print) | |
# print the number of files here, to both stdout and stderr | |
printf "%d %s\n" $nfiles "$dir" | tee /dev/stderr | |
} | |
countFiles $1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment