UNIX in a Nutshell: System V Edition

UNIX in a Nutshell: System V EditionSearch this book
Previous: Reference: fgChapter 5
The C Shell
Next: Reference: glob
 

foreach

foreach name (wordlist)
     commands
end

Assign variable name to each value in wordlist, and execute commands between foreach and end. You can use foreach as a multiline command issued at the C shell prompt (first Example), or you can use it in a shell script (second Example).

Examples

Rename all files that begin with a capital letter:

% foreach i ([A-Z]*)
? mv $i $i.new
? end

Check whether each command-line argument is an option or not:

foreach arg ($argv)
   # does it begin with - ?
   if ("$arg" =~ -*) then
      echo "Argument is an option"
   else
      echo "Argument is a filename"
   endif
end


Previous: Reference: fgUNIX in a Nutshell: System V EditionNext: Reference: glob
Reference: fgBook IndexReference: glob

The UNIX CD Bookshelf NavigationThe UNIX CD BookshelfUNIX Power ToolsUNIX in a NutshellLearning the vi Editorsed & awkLearning the Korn ShellLearning the UNIX Operating System