How to get list of all directory in Unix

Unix and Linux

 

We get such kind of requirement where we need to find all existing directory including sub-directories.

This is very basic requirement and interview question as well. To find out all existing directory list we will use only basic command like-

ls:- ls command is used for listing files and directory.

grep:- grep command is used for search record or line and files which have any specific word.

So final command is below

ls –l /* | grep ^d

Example:-

ls –l /* will  gives you list of all files and directory along with other attributes like permission, user, size of file or directory and created date etc. We will use first attribute to identify whether it is directory or file. First character of first attribute tell us whether it is directory or file.

drwxr-xr-x

-rwxr-xr-x

Which starts with “d”, it means that is directory.

Which start with “-“, it means that is file.

(it will collect directory and file list form root “/” directory including recursive. that is why “/” is used in command) .

drwxr-xr-x 1 user1 group1 2134 Dec 15 2018 Dir1 (it is directory)

drwxr-xr-x 2 user1 group1 1546 Oct 15 2018 Dir2 (it is directory)

drwxr-xr-x 1 user1 group1 2058 Dec 24 2018 Dir3 (it is directory)

drwxr-xr-x 15 user1 group1 1564 Dec 15 2018 Dir4 (it is directory)

-rwxr-xr-x 1 user1 group1 2134 Dec 15 2018 file1.txt (it is file)

drwxrwxr-x 1 user1 group1 6548 Dec 15 2018 Dir5 (it is directory)

-rwxrwxr-x 1 user1 group1 2134 Dec 15 2018 file2.txt (it is file)

-rwxrwxr-x 1 user1 group1 2134 Dec 15 2018 file3.txt (it is file)

-rwxrwxr-x 1 user1 group1 2134 Dec 15 2018 file4.txt (it is file)

 

Note: –  list which start with “d” is directory. So for getting all directory only we need to grep list which start with”d”.

ls –l* / | grep ^d (grep  ^d will filter out all list which starts with “d”)

 

drwxr-xr-x 1 user1 group1 2134 Dec 15 2018 Dir1 (it is directory)

drwxr-xr-x 2 user1 group1 1546 Oct 15 2018 Dir2 (it is directory)

drwxr-xr-x 1 user1 group1 2058 Dec 24 2018 Dir3 (it is directory)

drwxr-xr-x 15 user1 group1 1564 Dec 15 2018 Dir4 (it is directory)

drwxrwxr-x 1 user1 group1 6548 Dec 15 2018 Dir5 (it is directory)

 

All attribute of ls -l in Unix/Linux

 

Leave a Reply

Your email address will not be published. Required fields are marked *