Helpful Information
 
 
Category: UNIX Help
Don't understand simple for loop in shell script

I've taken over another programmer's code and need a little help with a simple shell script. The previous programmer wrote a script to descend down into a number of directories and make every file in the directory a symbolic link to a directory above it. There's one part, that although I'm positive is simple, I don't understand. Plus, I don't have a good resource for shell scripting, so I've come here. Here's the part the confuses me:

# The code cds into a directory a few lines before

for d in et00?
do
if [-d "$d" ]
then
echo Entering directory $d ...
cd $d
# rest of code

Based on where the shell script cds into, et001 et002 et003 et004 and et005 are five directories that match the et00?. There are other directories, but these would match if you were to create a regexp. Somehow this loop runs five times with $d equalling the directory names above on each pass.

This confuses me and I'll tell you why. I realize that ? is a wildcard and will match any character. However $d seems to somehow know that it's supposed to look at the directory structure and make matches on that. But it seems like steps are missing in the above code snippet. For example

for d in et00?
do
echo $d
done

prints out et001 et002 et003 et004 and et005. But what on earth is directing it to do a regexp match on the directories? Any help would be greatly appreciated.

"for (d in ..." will always go for files/directories.

"if [-d "$d" ]" is the short form for:
if test -d "$d"
and "test" also refers to files/directories.

read the bash manual, it explains everything. in SuSE it is /usr/share/doc/packages/bash/bashref.html

for a simple example:


for i in *.txt; do
echo $i
done

will output all ".txt" files
and:


for i in *; do
if [ -d "$i" ]; then
echo "$i is a folder."
else
if [ -x "$i" ]; then
echo "$i is executable"
else
if [ -f "$i" ]; then
echo "$i is a file."
fi
fi
fi
done

you should now be able to guess... ;)

Ok, I'll read the bash manual, as you suggested. It seems a little foreign to me, however. To me, I always expect for loops to do what for loops do, which is iterate through a sequence of things that you specify. As you've explained it, it almost seems as though for loops in shell programming are tailor made just to look through directories. Again, I'll start reading documentation and educate myself. Thanks.

itīs not the "for" loop. it does what you said.
it is the "*" and "?" that always expand to file names and the "test" function. the bash manual chapter about this is "substitution" and iirc the paragraph "filename substitution".

Thanks for the info!










privacy (GDPR)