January 21st, 2003, 02:03 PM
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?
if [-d "$d" ]
echo Entering directory $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?
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.
January 21st, 2003, 02:41 PM
"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:
will output all ".txt" files
for i in *.txt; do
you should now be able to guess...
for i in *; do
if [ -d "$i" ]; then
echo "$i is a folder."
if [ -x "$i" ]; then
echo "$i is executable"
if [ -f "$i" ]; then
echo "$i is a file."
January 21st, 2003, 07:15 PM
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.
January 22nd, 2003, 01:00 AM
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".
January 22nd, 2003, 07:34 AM