How to count number of folders in folder|directory in Linux?

Written by Administrator on Saturday April 11, 2020

To count number of folders/directories/files in folder/directory is possible using wc command with a parameter -l. But we have to be sure, that we are counting only folders, so let's filter only folder using ls command, and then count then.

My example:

$ pwd
/home/dima/

Then let's take a look, which files and folders we have:

$ ls

output:

Ah, we have folders and files. let's filter only folders:

$ ls -d /*

Now, let's combine two commands 1) filter only folders 2) count entities found (in our case: count the result of wc -l command).

$ ls -d /* | wc -l

output:

As you see, result of running a command is correct: we really have 16 directories in /home/dima directory.

Counting folder and subfolders

In case you want recursively find and count all folders and subfolder of selected folder, you can use chaing of commands. First, you define the depth of going to count subdirectories, then you print them and then you're using wc tool to count the result of previous commands. For example, my home folder is /home/dima and I want to count all folders and subfolers in this directory (I'm setting -maxdepth parameter to almost indefinite to be sure):

$ find /home/dima -maxdepth 100 -type d -print| wc -l

What will I get?

BTW, in case you have only folders/directories in selected folder/directory:

$ ls | wc -l

This command count folders and directories, but in case you have only folders in your folder, this command just works (because you don't have files).

Category: linux Tags: opensuse wc ls