开发者

List the contents of all subdirectories of the current directory - parse ls vs. globbing

In the book "Beginning Portable Shell Scripting" by Peter Seebach there is an example how to list the contents of all subdirectories of the current directory:

#!/bin/sh
/bin/ls | while read file
do
  if test -d "$file"; then
   ( cd "$file" && ls )
  fi
done

I learned th开发者_JAVA百科at parsing ls is bad and globbing should be prefered. Do you think the author chooses parsing because there is a portability issue?

I would do:

#!/bin/sh
for file in *
do
 if test -d "$file"; then
  ( cd "$file" && ls )
 fi
done

Thanks,

Somebody


Both solutions are not robust against weird filenames, nor do they handle directories which begin with ".". I would write this using find, e.g.:

find . -maxdepth 1 -type d -exec ls '{}' ';'

but first I'd question what output is actually required, either for a person to eyeball or a further script to digest.

You'll probably be able to do in a single "find" what is going to cost a lot of process forks with the for/while ... do ... done loop.


Globbing is much preferred over parsing ls since it will handle filenames that include spaces and other characters.

For the specific case in your question, you may be able to use nothing more than:

ls */
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜