Viewing Number of Subdirectories and Files in Raspberry Pi?
There are multiple commands to display the list or find the files inside directories or subdirectories:
1: Through ls and wc commands
2: Through tree command
3: Through find command
1: ls Command to Find Number of Files and Directories/Sub-Directories
To find all the files or directories inside a directory an ls command is used. The ls command will display everything present inside a directory whether it is a file or a sub-directory. From here you can count the files or sub-directories:
If you do not want to count the number manually then by using the below-written command the total number of files and sub-directories will be displayed by counting them using the wc command:
For example, in the image below, you can see that the total number of files and subdirectories inside my home directory is 68.
If you want to find the files and sub-directories inside a certain directory without switching to that directory, then you can simply ls with the name of that directory:
Syntax
Example
Here, I have viewed the contents of desktop and document directories:
$ ls Documents
And by using the same wc (word-count) command the total number of files and sub-directories in a directory can be displayed:
2: tree Command to Find Number of Files and Directories/Sub-Directories
The tree command can also be used to display the tree of files and sub-directories along with the total number of directories inside a directory or system. It can either be used to display all the content inside a certain user or a directory:
The output will display a tree of all files and directories, and the total number of files and directories will be displayed at the bottom, which is highlighted in the image:
If you just want the sum of all the sub-directories and files number inside a directory, then add wc -l with the tree command and it will display the number:
3: find Command to Find Number of Files in a Directory/Sub-Directories
If you only want to display the number of files inside a directory excluding subdirectories, then the below-written find command can be used:
The output will display all the files present inside a directory
And if you only want the number for a file simply pipe word count (wc) command with it:
Conclusion
Different commands to find the number of files and sub-directories inside a directory are used which are discussed in detail in the article. The ls command is used to list all the files and subdirectories. Whereas, the tree command will give a complete tree of the content present inside the file, and if you only want the total number of sub-directories and files then the pipe wc command to give you a count of files plus sub-directories.