Objective: Count the number of files in a directory on Unix or Linux.
Use the ls
and wc
commands to get the file count in a directory. Hidden files (files that start with “.”) will be excluded from the count. If there are sub directories or soft links (symbolic links) within that directory, they will be counted as a file as well. Use one of the following syntax.
1 |
$ ls -1 /path/to/directory | wc -l |
1 |
$ ls -l /path/to/directory | tail -n +2 | wc -l |
If you are only interested in counting regular files, including hidden files, use the find command. Note that the “maxdepth
” option is not supported in some Unix distributions. GNU find
supports the “maxdepth
” option. The below syntax will not include soft links.
1 |
$ find /path/to/directory -type f -maxdepth 1 | wc -l |
To count all regular files, including hidden files and soft links, use the “-L
” option.
1 |
$ find -L /path/to/directory -type f -maxdepth 1 | wc -l |
To count the number of executable files, use the “-perm
” option. Again, this syntax only works with GNU find
.
1 |
$ find /path/to/directory -maxdepth 1 -type f -perm /111 | wc -l |