Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Is there a built-in command or a less verbose way of achieving this?

find /var/foo -maxdepth 1 -mindepth 1 -type d

Or should I just make a tiny shell script or function if I'm doing this sort of thing often?

share|improve this question

2 Answers 2

ls -d */

"-d" means don't delve into the directories, the "*/" only matches directories.

share|improve this answer
    
+1 for globbing. –  Warner Mar 26 '10 at 21:45
    
What about directories that start with a "." ? I have edited my question since the title asks for subdirectories, and specifying only maxdepth also returns ./ which is not desired –  Bribles Mar 27 '10 at 0:01
    
"ls -d .[A-z0-9]*" will catch most (but not necessarily all). –  mibus Mar 31 '10 at 4:02
    
Well, you'd need to do ls -d */ .[A-z0-9]*/ to get both regular and a subset of hidden files. –  Bribles Mar 31 '10 at 21:52
up vote 1 down vote accepted

The shortest command seems to be

ls -d /var/foo/{*,.[^.]*,..[^.]*}/

I believe that will non-recursively list all the subdirectories of /var/foo, no matter how stupidly named the directories are or if non-ASCII characters are involved.

user@comp:~$ ls -1d /var/foo/{*,.[^.]*,..[^.]*}/
/var/foo/ . . . . . /
/var/foo/-d/
/var/foo/. . . . . ./
/var/foo/. d/
/var/foo/.-d/
/var/foo/..d/
/var/foo/.d/
/var/foo/.字_Ж/
/var/foo/d/
/var/foo/dir1/
/var/foo/dir2/
/var/foo/字/

However, find /var/foo -maxdepth 1 -mindepth 1 -type d is easier to both remember and type.

Below is my original self-answer.

If one cares not about files beginning with a dot then mibus' answer of

ls -d /var/foo/*/

would be short and effective. However if one would like the hidden files to be included then one needs to either stick with

find /var/foo -maxdepth 1 -mindepth 1 -type d

or try

ls -FA /var/foo | grep /

The -F places / and the end of directory names (as well as other characters for other types of files). The -A causes files starting with a dot to be included, except for '.' and '..'. That is why -a is not used. The grep won't get any false positives since '/' is not allowed in filenames (at least for POSIX filesystems).

Regarding performance, on my Ubuntu Jaunty installation with just shy of 32k files and directories in /var/foo, find is the fastest, followed by ls -d, and ls -FA with grep comes in last.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.