Friday, September 18, 2009

Simplifying Loopy Code


The determined Real Programmer can write FORTRAN programs in any language.
I just read through a friend's shell script. He doesn't program in the shell much, but he's a superb C programmer, so his script has loops that look like this:
file[0]=foo
file[1]=bar
file[2]=mumble
suffix[0]=.c
suffix[1]=.h
suffix[2]=.txt

nfiles=${#file[@]}
nsuffixes=${#suffix[@]}


i=0while [ $i -lt $nfiles ]
do
j=0
while [ $j -lt $nsuffixes ]
do
process ${file[$i]}${suffix[$j]}
(( j = j + 1 ))
done
(( i = i + 1 ))
done
Yep. That'll work. But this will, too.
for filename in {foo,bar,mumble}.{c,h,txt}
do

process $filename
done
Bash sees filenames as strings, and most shell commands accept space-separated lists of filenames. The shell handles anything that expands to a list of filenames, like globs or brace expansions, with real ease.

Use the Shell, Luke.

No comments: