tags:

views:

142

answers:

7

I have most of what I need so far I'm just unsure of the grep command to get only directories or if there isn't one. For context, this is the original request:

This script should take a single command line argument which will be a path to a directory. (done) The script should make sure that the path is, in fact, a directory and that the user had read permission on it. (done) Your program should then capture the output of an ls command on the directory. (done) It should then print out the names of only the sub-directories that are found. Files should be ignored. (???)

I have so far:

#!/bin/bash

if [ -d $1 ] && [ -r $1 ] ; then 
  ls -l $1 | tee output | grep  ______
fi
+1  A: 

The -p option for ls will probably be useful. See man ls.

too much php
+6  A: 

do a grep

ls -l | grep '^d'

or just use find

find $1 -type d
ghostdog74
THanks this works perfectly
roger34
+1 for `find`. `find` is recursive, though, so it *may* not be what is desired.
strager
You can control the recursion. See Andy Ross's answer.
Dennis Williamson
+2  A: 
John Kugelman
A: 

ls -l . | awk '/^d/{printf "%s ",$8}'

Although the argument$8 depends on output of ls -l at your machine

Neeraj
yes, especially if there are files with spaces. $8 will not be sufficient.
ghostdog74
+1  A: 
find $1 -maxdepth 1 -type d

also works well. If the awk example above counts, you might as well include perl:

grep -d, glob("$path/*")

... will get you a list of directories when called in an array context.

Andy Ross
One might also want to use -mindepth 1 as well.
Mark Edgar
+1  A: 

ls is "eyes-only"

See: Parsing ls

find is the correct command to use. See Andy Ross's answer.

Dennis Williamson
A: 

You probably don't need the -d or -r checks:

shopt -s failglob
echo "$1"/*/.

Replace echo with the thing you really want to do (your original question doesn't say).

Mark Edgar