Count files in a directory with bash

Posted by Dark Training on May 12, 2009 tags: | bash | linux

So the problem is that you have a script that needs to count how many files are in a directory in order to perform a function, but how do you do it"

ls -1|wc -l

That will give you the number, but it's also counting any folders, we just want files.

ls -R1 /path|grep -v /|grep -vx ""|grep -vx "\.*"|wc -l

If we wanted to include hidden files we would use:

ls -Ra1 /disk_array/backups/|grep -v /|grep -vx ""|grep -vx "\.*"|wc -l

If we want to exclude directory in that path from being counted:

ls -Ra1 /disk_array/backups/|grep -v /path to exclude|grep -v /|grep -vx ""|grep -vx "\.*"|wc -l