Looping Construct in CSH

441 Views Asked by At

I'm new to Unix scripting. I'm a little confused on how the construct works for looping through multiple variables. I'm trying to grab a .grb2 file and for all dates and times specified. Here is my script....

#!/bin/csh

set  fhrs="nl"
set  dd="09 10 11 12 13 14"
set  runs="00 06 12 18"

foreach fhrs ($fhrs)
foreach dd ($dd)
foreach runs ($runs)

wget http://nomads.ncdc.noaa.gov/modeldata/cmd_pgbh/2004/200408/200408$dd/pgbh$fhrs.gdas.200408$dd$runs.grb2

end
end
end

My output goes through the first iteration namely dd=9 and runs=00 through runs=18. Once it gets to the end it just does the runs=18 for the rest of the dates(dd). How do I get it loop back and start over? Is there a "continue" statement in csh? Do I need to add an if statement? I've tried nesting the foreach and set statements but that didn't work. Any guidance would be greatly appreciated! Thanks!

1

There are 1 best solutions below

1
On

I'm not sure what you're trying to accomplish with the fhrs variable.

Realize you only have one loop value at the top, fhrs. Move that to the inner-most loop and you should see the other loops "fire" as you need.

Also, you should use a different names for all your iterator variables, like

foreach f_hrs ($fhrs)
foreach d_d ($dd)
foreach r ($runs) 

edit This is because each time a loop assigns something to a variable, it destroys what was there previously (at the end of the loop). You are using the same name to hold both your list, as well as the unique values used for each loop, so for your runs case, you start out with

runs="00 06 12 18"
runs="00"
runs="06"
runs="12"

and on the last loop of processing runs (and for the next run of your dd loop (which is also wiped out now), you have only

runs="18"

So the next time the runs loop is executed, you get only runs="18"

You would see this happening very easily, if you turn
on csh debugging/trace to see what is going on if with

#!/bin/csh -vx

OR just change (temporarily) to

echo wget ..

If that doesn't help, add a special debugging line like

echo 200408$dd/pgbh$fhrs.gdas.200408$dd$runs.grb2

and add the last ~6 lines of output into your question to illustrate your problem.

Finally, yes, csh has both a continue and break statement that work inside loops. See csh flow control for the whole story.

IHTH.