开发者

Printing out names of only directories and not files (BASH)

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 s开发者_StackOverflow中文版hould 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


do a grep

ls -l | grep '^d'

or just use find

find $1 -type d


Hint — from man ls:

-F ... Display a slash (/) immediately after each pathname that is a directory, an asterisk (*) after each that is executable, an at sign (@) after each symbolic link, an equals sign (=) after each socket, a percent sign (%) after each whiteout, and a vertical bar (|) after each that is a FIFO.

-p ... Write a slash (/) after each filename if that file is a directory.


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


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.


ls is "eyes-only"

See: Parsing ls

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



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

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


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜