How To List Directories in a Directory in Unix

Another quick answer to the question I see a lot in search queries on this blog: listing directories in a directory. I take it that this question means showing a list of only the directories and not other files under a certain location of your Unix filesystem.

Using find to show only directories

find command helps you show only the directories by using a -type d parameter.

Compare the default find output of finding files and directories under /etc/mysql:

ubuntu# find /etc/mysql 

To the one which only shows you the directories:

ubuntu# find /etc/mysql -type d

And if you're in doubt, you can always use ls -ld command to confirm that returned entries are really standard Unix directories:

ubuntu# ls -ld /etc/mysql /etc/mysql/conf.d
drwxr-xr-x 3 root root 4096 2008-03-28 07:56 /etc/mysql
drwxr-xr-x 2 root root 4096 2008-03-25 21:06 /etc/mysql/conf.d

That's it! Have fun with Unix!

See also:

  • Tom

    Often the output of find is a list of files that contain nos standard characters for file names, such as spaces, apostrophes, parenthesis,…. I know it's a bad practice but sometimes a lot of files (especially, audio files) come from remote sources. So, if we haven't renamed those files, the output of find can give unexpected results when it is directed to a pipe to be ussed by a second program.

    How can we get an autput that programs understand to name files?

  • mr_dole

    For shell programming I find these three methods useful.

    Example 1: From current working directory return directory name only

    $ ls -d *

    bin ect kernel opt sbin tmp usr var

    Example 2: From current working directory include local directory "./"

    $ ls -d ./*

    ./bin ./ect ./kernel ./opt ./sbin ./tmp ./usr ./var

    Eample 3: Provide the full path and return the directories with the full path name

    $ ls -d /*

    /bin /ect /kernel /opt /sbin /tmp /usr /var

    $ ls -d /usr/*

    /usr/bin /usr/include /usr/lib /usr/sbin

    Shell programming usage example: This should work with Bourn, Korn and Bash

    print "Parent: $parent_directory"

    # Get pull path for directories in $parent_directory
    /bin/ls -d ${parent_directory}/* |
    while read child_directory; do
    print " Child: $child_directory"

    Hope this is useful..

  • vovets

    2Tom: sometimes one can use -print0 primary. For example
    find . -type f -name '*~' -print0 | xargs -0 rm

  • rod

    Thanks for telling us about that, mate!
    Another good and easy tip for listing directories is by using grep with the output of ls command. Then you have:

    ls -l | grep ^d

    That's it.
    Try it yourself.

  • U should not use LS….. try find only the directory using FIND command

  • Pingback: Compare Directories in Unix using diff command | Unix Tutorial()