Name

foreach

Synopsis

    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 shell prompt (first of the following examples), 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]*)
    foreach? mv $i $i.old
    foreach?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

Get Unix in a Nutshell, 4th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.