[sf-lug] bash: identifying directories
asheesh at asheesh.org
Sat Jun 7 11:37:14 PDT 2008
On Tue, 3 Jun 2008, Matt Price wrote:
> another little scripting question:
> i'd like this tiny script i'm writing to scan the current directory,
> identify the subdirectories, and then do something in each of them. so
> in pseudocode:
> [find dirs]
> for DIR in $dirs ; do
> cd $DIR
> [do some stuff]
> cd ..
As MP suggested, you use "find -type d" if you really want just
directories. But if you do that, you're going to end up accidentally sad
if there are spaces in their filenames, or intentionally careful to avoid
But here is what I would do:
$ for thing in *
if [ -d "$thing" ]
echo -n "Look at me, I am in "
Two things to notice here:
1. the -d test in bash will ask if "$thing" is a directory. I'm careful
to quote its name, so it'll work properly given all sorts of embedded
2. "pushd" and "popd" are some of my favorite commands. Play with them -
they let you go into a directory, and then go *anywhere else* and then
"popd" back to the place you were when you issued the "pushd" command.
So you can do:
and you're still back in $HOME! Joyful for iterating across directories.
P.S. You're leaving town soon, right? )-:
As a goatherd learns his trade by goat, so a writer learns his trade by wrote.
More information about the sf-lug