To find the total number of regular files in directory $1
and its subdirectories:
find "$1" -type f -printf "1\n" | wc -l
To save that number in a variable:
var=$(find "$1" -type f -printf "1\n" | wc -l)
This will work even if file or directory names contain white space or other difficult characters.
Discussion
Let us consider this line from the original code:
for x in `ls -lr $1 | grep "^d" | tr -s ' ' | cut -d ' ' -f 9`;
First, one should never parse ls. It is unreliable. The output of ls
changes from one version to the next. Further, because of the way special characters are treated, the name displayed by ls
is not necessarily the correct name of the file or directory.
Second, when using shell variables, like $1
, they should be in double-quotes. Otherwise word splitting and pathname expansion is performed on them which can lead to all manor of errors.
Third, in a form like:
for x in `...`
the shell will perform word splitting and pathname expansion on the result of the command substitution. This can also lead to all manor of errors.
return
orunset
?