Recursive shell script - most elegant implementation?
Posted on 2002-05-30
I've been working on a shell script to rename files in a directory tree. The purpose is to remove spaces from the file names of some photos so that they can be more easily put on the web (fewer %20 instances). I'm working in the Bourne shell, and have mastered the task of renaming all the files in the current directory, using a "for Original in *" type of construct to look at each file the directory, squeeze the spaces out of it, rename it. The current implementation looks something like this (from memory, may not be perfect):
for Original in *
Squeezed = `echo $Original | sed 's/ //g'`
if [ "$Original" != $Squeezed ]
mv \"$Original\" $Squeezed
The next advancement I'd like to make is to recursively run the script - test each file with [ -d $Squeezed ] and then call the script to work on the new directory.
The trouble is how to refer to the script itself in order to run it successively from various places within the directory tree. The solutions that come to mind are:
1. copy the script to tmp and execute it from that fixed location, then delete it when done, a la
cp $0 /tmp/$$.sqzit
<do recursive stuff>
2. Put the whole working part of the script into a Here document, then copy that into each directory as we go and execute it from there (whew, the conceptual image of that is interesting). Kind of makes it into a two part script.
Usually when I find myself proposing a solution this complicated I later discover that Unix has some obscure but elegant way to accomplish what I'm trying to do... does anyone have any simple way to run a new instance of the script that is currently running, in a new directory and with a new command line?
Suggestions and pointers to good scripting tutorials/resources on the web welcome.