csh/C Shell Scripts: for Loop Syntax

A for loop allows a program to iterate over a set of values. For loops in a C shell script are a useful means of iterating through files or other lists. This recipe describes the for loop syntax and provides some examples.


The basic for loop syntax is as follows:

foreach var (list)
commands;
end

The list can be a specified set of values (1 2 3 4) or anything that will evaluate into a set of values (A wildcard expression will expand the matching filenames into a list.). For example, ‘/usr/bin/[aeiou]*’ will expand to the set of files in /usr/bin starting with a vowel (This, of course, comes up all the time.). The commands enclosed between do and done will be executed once for each item in the list. The current value from the set can be accessed with the variable $var.

To separate a log file into multiple files based on the month (assuming that the log format contains a capitalized three-letter month abbreviation), use the following:

#!/bin/csh
logfile="/var/adm/messages"
foreach mon (Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec)
grep $mon $logfile > $logfile.$mon
end

The Conversation

Follow the reactions below and share your own thoughts.

  • Anonymous

    These aren’t months. What? :-P

  • kranthi

    if u dnt know how to use for loop in cshell script why did u mention above for loop plz remove that and place the foreach loop…..dnt iritate people plzzzzzzzzzzzzz………