List directories without erroring if none exist

2

I have a rather strict set of specs for a directory listing that I need:

  1. It must list the directories in the current directory
  2. It must list purely the basename (no "./", no trailing slash)
  3. It mustn't error if there are none (and mustn't print an error to std{out,err})
  4. It must be very lightweight
  5. It must work under tcsh

I've got something working like this:

find -maxdepth 1 -mindepth 1 -type d -printf '%f\n'

But I can't help feeling that using "find" is overkill. I tried to do something with ls -d */, but I couldn't figure out how to get it not error (or appear to not error).

Any suggestions?

spookypeanut

Posted 2013-03-26T14:19:18.647

Reputation: 207

How do you need the output? ls-style or one per line? – Dennis – 2013-03-26T14:32:28.423

This is for a tcsh completion, which I think means either will work (I can't use the standard directory completion, for reasons I won't go into right now). – spookypeanut – 2013-03-26T16:48:38.323

Answers

1

Personally, I'd say the find command is the way to go.

The ls -d approach has two problems right now:

  • It shows an error on empty directories.
  • It prints trailing slashes.

Both are fixable. tr can take care of the slashes, and you need redirection to get rid of error messages:

( ls -d */ | tr -d / > /dev/tty ) > & /dev/null

See man tcsh for further information.

Dennis

Posted 2013-03-26T14:19:18.647

Reputation: 42 934