[sf-lug] bash: identifying directories

Asheesh Laroia 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 ..
> done

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 
that problem.

But here is what I would do:

$ for thing in *
do
  if [ -d "$thing" ]
  then
    pushd "$thing"
    echo -n "Look at me, I am in "
    pwd
    popd
  fi
  done

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

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:

cd $HOME
pushd /tmp
mkdir lalaland
cd lalaland
touch me
popd

and you're still back in $HOME!  Joyful for iterating across directories.

-- Asheesh.

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 mailing list