Doing UNIX Shell For Loops The Right Way
2009 March 16
Typically for loops in UNIX shell look like this:
for file in `ls *.c` do cmd $file done
However, the above has a serious problem in that it does not handle spaces in file names and will actually split the filename in two.
The following is a solution in bash:
files=(*.c)
for f in “${files[@]}”
do
cmd "$f"
done
But my favourite way to perform a loop and probably the most elegant solution is to use file globbing:
for f in *.c do cmd "$f" done