[PLUG] listing only directories

Eric Wilhelm scratchcomputing at gmail.com
Sun Oct 7 22:30:05 UTC 2007


# from Paul Mullen
# on Sunday 07 October 2007 13:09:

>> How do you use the ls command to list ONLY directories, no files?
>
>I don't know that ls has a simple way to list only directories, but
>there are a few workarounds:

No need for workarounds (at least with gnu bash and ls.)

  ls -d */

But that relies on the shell glob */ expanding to all of the 
directories, which means it can't be inverted to "just files" (i.e. 
*[!/] won't do) because glob's won't match / (or leading .) with a 
wildcard (not even in Denmark.)  So, the "invertable pair" is:

  find -maxdepth 1 -type d
  find -maxdepth 1 -not -type d

...but that lists hidden files, so...

  find -maxdepth 1 -type d -not -name '.*'
  find -maxdepth 1 -not -type d -not -name '.*'

And if your vendor is mean enough (bsd/mac) to deprive you of a gnu 
userland, the first argument to find has to be an explicit '.'

  find . -maxdepth 1 -type d -not -name '.*'
  find . -maxdepth 1 -not -type d -not -name '.*'

(or else you'll get the unhelpful:

  find: illegal option -- m
  find: illegal option -- a
  find: illegal option -- e
  find: illegal option -- p
  find: illegal option -- t
  find: illegal option -- h
  find: 1: No such file or directory
)

So, back to our cozy linux box:

  ls --file-type | grep -v '/$'

or (heh)

  ls -- $(ls -l | grep -v '^d') 2>/dev/null

That last one has plenty of caveats though ;-)  (i.e "Professional 
driver, closed course.  Do not attempt.")

You might want to make aliases for 'files'

  alias files="find . -maxdepth 1 -not -type d -not -name '.*' \
    | sed 's/^.\///'"

Then you can have your colors back (but -a won't work here)

  ls $(files)

For continuing fun, see `help alias` and the manpages for ls, find, and 
glob and the bash manual:
  http://www.gnu.org/software/bash/manual/bashref.html#SEC26

specifically:
  http://www.gnu.org/software/bash/manual/bashref.html#SEC30

--Eric
-- 
So malloc calls a timeout and starts rummaging around the free chain,
sorting things out, and merging adjacent small free blocks into larger
blocks. This takes 3 1/2 days.
--Joel Spolsky
---------------------------------------------------
    http://scratchcomputing.com
---------------------------------------------------



More information about the PLUG mailing list