Making a for Loop with Multiple Variables

Unix Power Tools
Making a for Loop with Multiple Variables

by Jerry Peek
02/10/2000

The normal Bourne shell for loop lets you take a list of items, store the items one by one in a shell variable, and loop through a set of commands once for each item:

for file in prog1 prog2 prog3

do

    ...process $file   

done

I wanted a for loop that stores several different shell variables and makes one pass through the loop for each set of variables (instead of one pass for each item, as a regular for loop does). This loop does the job:

for bunch in "ellie file16" "donna file23" "steve file34"

do

   # PUT FIRST WORD (USER) IN $1, SECOND (FILE) IN $2...

   set $bunch

   mail $1 < $2

done

If you have any command-line arguments and still need them, store them in another variable before you do that. Or, you can make the loop this way:

for bunch in "u=ellie f=file16 s='your files'" \

    "u=donna f=file23 s='a memo'" "u=steve f=file34 s=report"

do

   # SET $u (USER), $f (FILENAME), $s (SUBJECT):

   eval $bunch

   mail -s "$s" $u < $f

done

This script uses the shell's eval command to re-scan the contents of the bunch variable and store it in separate variables. Notice the single quotes like s='your files'; this groups the words for eval. The shell removes those single quotes before it stores the value into the s variable.


Back More Unix Power Tools

 

Close    To Top
  • Prev Article-OS:
  • Next Article-OS:
  • Now: Tutorial for Web and Software Design > OS > Linux > OS Content
    Photoshop Tutorial
     

    Special Effect

      3D Effect
      Photoshop Articles
    Programming Tutorial
     

    C/C++ Tutorial

      Visual Basic
      C# Tutorial
    Database Tutorial
     

    MySQL Tutorial

      MS SQL Tutorial
      Oracle Tutorial
    Geek Tutorial
     

    Blogging Tutorial

      RSS Tutorial
      Podcasting Tutorial
    Graphic Design Tutorial
      Coreldraw Tutorial
      Illustrator Tutorial
      3D Tutorials
    Webmaster Articles
     

    Domain Service

      Web Hosting
      Site Promotion
    Java Tutorial/ Articles
     

    Java Servlets

      JavaEE Tutorial
     

    JavaBeans Tutorial

    XML Tutorial/ Articles
     

    XML Style

      AJAX Tutorial
      XML Mobile
    Flash Tutorial/ Articles
     

    Flash Video

      Action Script
      Flash Articles
    OS Tutorial/ Articles
      Linux Tutorial
      Symbian Tutorial
      MacOS Tutorial
    Personal Tech
      Hardware Tutorial
      Software Tutorial
      Online Auction